Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 使用ruby中不同哈希数组中的元素创建哈希_Arrays_Ruby_Hash - Fatal编程技术网

Arrays 使用ruby中不同哈希数组中的元素创建哈希

Arrays 使用ruby中不同哈希数组中的元素创建哈希,arrays,ruby,hash,Arrays,Ruby,Hash,在一次训练营练习中,我们获得了以下阵列: library = [ { "title" => "Hitchhiker's Guide", "Author" => "Douglas Adams", "categories" => [ "comedy", "fiction", "british"] }, { "title" => "Pride and Prejudice", "Author" => "Jane Au

在一次训练营练习中,我们获得了以下阵列:

library = [
  {
    "title" => "Hitchhiker's Guide", 
    "Author" => "Douglas Adams", 
    "categories" => [ "comedy", "fiction", "british"]
  },
  {
    "title" => "Pride and Prejudice", 
    "Author" => "Jane Austen", 
    "categories" => [ "morality", "fiction", "society", "british"]
  },
  {
    "title" => "Search Inside Yourself", 
    "Author" => "Chade-Meng Tan", 
    "categories" => [ "self improvement", "non-fiction", "mindfulness", "business"]
  },
  {
    "title" => "Benjamin Franklin: An American Life", 
    "Author" => "Walter Isaacson", 
    "categories" => [ "non-fiction", "history", "founding fathers"]
  },
  {
    "title" => "Glengarry Glen Ross", 
    "Author" => "David Mamet", 
    "categories" => [ "play", "fiction", "drama"]
  }
]
我们需要创建一个新的散列,其中类别作为元素,标题作为值

我知道如何创建一个
类别\u散列
,但我不知道如何将标题附加到每个类别。这是我的密码:

category_hash = {}
sub_category = []

library.each do |book|
  book["categories"].each do |category|
    sub_category << category
  end
  sub_category.each do |index|
    category_hash[index] = "I'm not sure how to append the titles here"
  end
end

p category_hash
category_hash={}
子类别=[]
图书馆。每本书|
书籍[“类别”]。每一本书都有一个类别|
子类别您可以使用:

您可以使用:


这里有另一种方法,比@AndreyDeineko的答案效率低

library.map{|h| h.values_at("categories", "title")}.to_h
结果:

{
  ["comedy", "fiction", "british"]=>"Hitchhiker's Guide", 
  ["morality", "fiction", "society", "british"]=>"Pride and Prejudice",
  ["self improvement", "non-fiction", "mindfulness", "business"]=>"Search Inside Yourself",
  ["non-fiction", "history", "founding fathers"]=>"Benjamin Franklin: An American Life",
  ["play", "fiction", "drama"]=>"Glengarry Glen Ross"
}
{
  "comedy"=>"Hitchhiker's Guide",
  "fiction"=>"Glengarry Glen Ross",
  "british"=>"Pride and Prejudice",
  "morality"=>"Pride and Prejudice",
  "society"=>"Pride and Prejudice",
  "self improvement"=>"Search Inside Yourself",
  "non-fiction"=>"Benjamin Franklin: An American Life", 
  "mindfulness"=>"Search Inside Yourself",
  "business"=>"Search Inside Yourself",
  "history"=>"Benjamin Franklin: An American Life",
  "founding fathers"=>"Benjamin Franklin: An American Life",
  "play"=>"Glengarry Glen Ross",
  "drama"=>"Glengarry Glen Ross"
}
{
  "comedy"=>["Hitchhiker's Guide"],
  "fiction"=>["Hitchhiker's Guide", "Pride and Prejudice", "Glengarry Glen Ross"],
  "british"=>["Hitchhiker's Guide", "Pride and Prejudice"],
  "morality"=>["Pride and Prejudice"],
  "society"=>["Pride and Prejudice"],
  "self improvement"=>["Search Inside Yourself"],
  "non-fiction"=>["Search Inside Yourself", "Benjamin Franklin: An American Life"],
  "mindfulness"=>["Search Inside Yourself"],
  "business"=>["Search Inside Yourself"],
  "history"=>["Benjamin Franklin: An American Life"],
  "founding fathers"=>["Benjamin Franklin: An American Life"],
  "play"=>["Glengarry Glen Ross"],
  "drama"=>["Glengarry Glen Ross"]
}
如果您希望通过
“category”
属性分发它(当然,这取决于数组中散列项的顺序;我假设您的意思是后面一个比前面一个优先):

结果:

{
  ["comedy", "fiction", "british"]=>"Hitchhiker's Guide", 
  ["morality", "fiction", "society", "british"]=>"Pride and Prejudice",
  ["self improvement", "non-fiction", "mindfulness", "business"]=>"Search Inside Yourself",
  ["non-fiction", "history", "founding fathers"]=>"Benjamin Franklin: An American Life",
  ["play", "fiction", "drama"]=>"Glengarry Glen Ross"
}
{
  "comedy"=>"Hitchhiker's Guide",
  "fiction"=>"Glengarry Glen Ross",
  "british"=>"Pride and Prejudice",
  "morality"=>"Pride and Prejudice",
  "society"=>"Pride and Prejudice",
  "self improvement"=>"Search Inside Yourself",
  "non-fiction"=>"Benjamin Franklin: An American Life", 
  "mindfulness"=>"Search Inside Yourself",
  "business"=>"Search Inside Yourself",
  "history"=>"Benjamin Franklin: An American Life",
  "founding fathers"=>"Benjamin Franklin: An American Life",
  "play"=>"Glengarry Glen Ross",
  "drama"=>"Glengarry Glen Ross"
}
{
  "comedy"=>["Hitchhiker's Guide"],
  "fiction"=>["Hitchhiker's Guide", "Pride and Prejudice", "Glengarry Glen Ross"],
  "british"=>["Hitchhiker's Guide", "Pride and Prejudice"],
  "morality"=>["Pride and Prejudice"],
  "society"=>["Pride and Prejudice"],
  "self improvement"=>["Search Inside Yourself"],
  "non-fiction"=>["Search Inside Yourself", "Benjamin Franklin: An American Life"],
  "mindfulness"=>["Search Inside Yourself"],
  "business"=>["Search Inside Yourself"],
  "history"=>["Benjamin Franklin: An American Life"],
  "founding fathers"=>["Benjamin Franklin: An American Life"],
  "play"=>["Glengarry Glen Ross"],
  "drama"=>["Glengarry Glen Ross"]
}

这里有另一种方法,比@AndreyDeineko的答案效率低

library.map{|h| h.values_at("categories", "title")}.to_h
结果:

{
  ["comedy", "fiction", "british"]=>"Hitchhiker's Guide", 
  ["morality", "fiction", "society", "british"]=>"Pride and Prejudice",
  ["self improvement", "non-fiction", "mindfulness", "business"]=>"Search Inside Yourself",
  ["non-fiction", "history", "founding fathers"]=>"Benjamin Franklin: An American Life",
  ["play", "fiction", "drama"]=>"Glengarry Glen Ross"
}
{
  "comedy"=>"Hitchhiker's Guide",
  "fiction"=>"Glengarry Glen Ross",
  "british"=>"Pride and Prejudice",
  "morality"=>"Pride and Prejudice",
  "society"=>"Pride and Prejudice",
  "self improvement"=>"Search Inside Yourself",
  "non-fiction"=>"Benjamin Franklin: An American Life", 
  "mindfulness"=>"Search Inside Yourself",
  "business"=>"Search Inside Yourself",
  "history"=>"Benjamin Franklin: An American Life",
  "founding fathers"=>"Benjamin Franklin: An American Life",
  "play"=>"Glengarry Glen Ross",
  "drama"=>"Glengarry Glen Ross"
}
{
  "comedy"=>["Hitchhiker's Guide"],
  "fiction"=>["Hitchhiker's Guide", "Pride and Prejudice", "Glengarry Glen Ross"],
  "british"=>["Hitchhiker's Guide", "Pride and Prejudice"],
  "morality"=>["Pride and Prejudice"],
  "society"=>["Pride and Prejudice"],
  "self improvement"=>["Search Inside Yourself"],
  "non-fiction"=>["Search Inside Yourself", "Benjamin Franklin: An American Life"],
  "mindfulness"=>["Search Inside Yourself"],
  "business"=>["Search Inside Yourself"],
  "history"=>["Benjamin Franklin: An American Life"],
  "founding fathers"=>["Benjamin Franklin: An American Life"],
  "play"=>["Glengarry Glen Ross"],
  "drama"=>["Glengarry Glen Ross"]
}
如果您希望通过
“category”
属性分发它(当然,这取决于数组中散列项的顺序;我假设您的意思是后面一个比前面一个优先):

结果:

{
  ["comedy", "fiction", "british"]=>"Hitchhiker's Guide", 
  ["morality", "fiction", "society", "british"]=>"Pride and Prejudice",
  ["self improvement", "non-fiction", "mindfulness", "business"]=>"Search Inside Yourself",
  ["non-fiction", "history", "founding fathers"]=>"Benjamin Franklin: An American Life",
  ["play", "fiction", "drama"]=>"Glengarry Glen Ross"
}
{
  "comedy"=>"Hitchhiker's Guide",
  "fiction"=>"Glengarry Glen Ross",
  "british"=>"Pride and Prejudice",
  "morality"=>"Pride and Prejudice",
  "society"=>"Pride and Prejudice",
  "self improvement"=>"Search Inside Yourself",
  "non-fiction"=>"Benjamin Franklin: An American Life", 
  "mindfulness"=>"Search Inside Yourself",
  "business"=>"Search Inside Yourself",
  "history"=>"Benjamin Franklin: An American Life",
  "founding fathers"=>"Benjamin Franklin: An American Life",
  "play"=>"Glengarry Glen Ross",
  "drama"=>"Glengarry Glen Ross"
}
{
  "comedy"=>["Hitchhiker's Guide"],
  "fiction"=>["Hitchhiker's Guide", "Pride and Prejudice", "Glengarry Glen Ross"],
  "british"=>["Hitchhiker's Guide", "Pride and Prejudice"],
  "morality"=>["Pride and Prejudice"],
  "society"=>["Pride and Prejudice"],
  "self improvement"=>["Search Inside Yourself"],
  "non-fiction"=>["Search Inside Yourself", "Benjamin Franklin: An American Life"],
  "mindfulness"=>["Search Inside Yourself"],
  "business"=>["Search Inside Yourself"],
  "history"=>["Benjamin Franklin: An American Life"],
  "founding fathers"=>["Benjamin Franklin: An American Life"],
  "play"=>["Glengarry Glen Ross"],
  "drama"=>["Glengarry Glen Ross"]
}

如果希望一个类别中每本书的列表,并且一本书显示在多个类别中,则可以在将所有未知键设置为包含数组作为值时附加。然后,您只需迭代库中的每本书,并将其标题添加到它所属的每个类别的列表中:

# Pass the category hash a default proc, which will be called
# whenever a key it doesn't have is accessed. So, when you
# encounter a brand new category, it'll already be set up with
# an array
category_hash = Hash.new { |hash, key| hash[key] = [] }
library.each do |book|
  book['categories'].each do |category|
    # since we passed the default, no worrying, an array will be
    # there and we can just add our value into it
    category_hash[category] << book['title']
  end
end

puts category_hash
还有
每个带有\u对象的\u
,因此您可以将其修改为

result = library.each.with_object(Hash.new { |hash, key| hash[key] = [] }) do |book, category_hash|
  book['categories'].each do |category|
    # since we passed the default, no worrying, an array will be
    # there and we can just add our value into it
    category_hash[category] << book['title']
  end
end
puts result

如果希望一个类别中每本书的列表,并且一本书显示在多个类别中,则可以在将所有未知键设置为包含数组作为值时附加。然后,您只需迭代库中的每本书,并将其标题添加到它所属的每个类别的列表中:

# Pass the category hash a default proc, which will be called
# whenever a key it doesn't have is accessed. So, when you
# encounter a brand new category, it'll already be set up with
# an array
category_hash = Hash.new { |hash, key| hash[key] = [] }
library.each do |book|
  book['categories'].each do |category|
    # since we passed the default, no worrying, an array will be
    # there and we can just add our value into it
    category_hash[category] << book['title']
  end
end

puts category_hash
还有
每个带有\u对象的\u
,因此您可以将其修改为

result = library.each.with_object(Hash.new { |hash, key| hash[key] = [] }) do |book, category_hash|
  book['categories'].each do |category|
    # since we passed the default, no worrying, an array will be
    # there and we can just add our value into it
    category_hash[category] << book['title']
  end
end
puts result

这与其他答案略有不同

library = [
  {title: "Hitch Guide", by: "Doug", cats: ["comedy", "fiction", "british"]},
  {title: "P and P",     by: "Jane", cats: ["morality", "fiction", "british"]},
  {title: "Searchin'",   by: "Chad", cats: ["non-fiction", "morality", "gps"]},
  {title: "Crazy Ben",   by: "Walt", cats: ["non-fiction", "comedy", "dads"]}
]
  # => [{:title=>"Hitch Guide", :by=>"Doug", :cats=>["comedy", "fiction", "british"]},
  #     {:title=>"P and P", :by=>"Jane", :cats=>["morality", "fiction", "british"]},
  #     {:title=>"Searchin'", :by=>"Chad", :cats=>["non-fiction", "morality", "gps"]},
  #     {:title=>"Crazy Ben", :by=>"Walt", :cats=>["non-fiction", "comedy", "dads"]}]

library.each_with_object({}) do |g,h|
  title = g[:title]
  g[:cats].each { |c| (h[c] ||= []) << title }
end
  #=> {"comedy"=>["Hitch Guide", "Crazy Ben"],
  #    "fiction"=>["Hitch Guide", "P and P"],
  #    "british"=>["Hitch Guide", "P and P"],
  #    "morality"=>["P and P", "Searchin'"],
  #    "non-fiction"=>["Searchin'", "Crazy Ben"],
  #    "gps"=>["Searchin'"],
  #    "dads"=>["Crazy Ben"]}
库=[
{标题:“搭便车指南”,作者:“道格”,猫:[“喜剧”、“小说”、“英国”]},
{标题:“P和P”,作者:“简”,猫:[“道德”、“小说”、“英国”]},
{标题:“搜索”,作者:“乍得”,猫:[“非小说”、“道德”、“全球定位系统”]},
{标题:“疯狂的本”,作者:“沃尔特”,猫:[“非小说”、“喜剧”、“爸爸”]}
]
#=>[{:title=>“搭便车指南”、:by=>“道格”、:cats=>[“喜剧”、“小说”、“英国”],
#{:title=>“P和P”,:by=>“Jane”,:cats=>[“道德”、“小说”、“英国”],
#{:title=>“Searchin'”,:by=>“Chad”,:cats=>[“非小说”、“道德”、“全球定位系统”]},
#{:title=>“疯狂的本”、:by=>“沃尔特”、:cats=>[“非小说”、“喜剧”、“爸爸”]}]
库。每个带有_对象({})do | g,h的|
title=g[:title]
g[:猫]。每只{| c |(h[c]| |=[]){“喜剧”=>[“搭车指南”,“疯狂本”],
#“小说”=>[“挂接指南”,“P和P”],
#“英国”=>[“挂接装置指南”,“P和P”],
#“道德”=>[“P和P”,“搜索],
#“非小说”=>[“搜索”,“疯狂本”],
#“gps”=>[“搜索””,
#“爸爸”=>[“疯狂的本”]}

这是其他答案的一个细微变化

library = [
  {title: "Hitch Guide", by: "Doug", cats: ["comedy", "fiction", "british"]},
  {title: "P and P",     by: "Jane", cats: ["morality", "fiction", "british"]},
  {title: "Searchin'",   by: "Chad", cats: ["non-fiction", "morality", "gps"]},
  {title: "Crazy Ben",   by: "Walt", cats: ["non-fiction", "comedy", "dads"]}
]
  # => [{:title=>"Hitch Guide", :by=>"Doug", :cats=>["comedy", "fiction", "british"]},
  #     {:title=>"P and P", :by=>"Jane", :cats=>["morality", "fiction", "british"]},
  #     {:title=>"Searchin'", :by=>"Chad", :cats=>["non-fiction", "morality", "gps"]},
  #     {:title=>"Crazy Ben", :by=>"Walt", :cats=>["non-fiction", "comedy", "dads"]}]

library.each_with_object({}) do |g,h|
  title = g[:title]
  g[:cats].each { |c| (h[c] ||= []) << title }
end
  #=> {"comedy"=>["Hitch Guide", "Crazy Ben"],
  #    "fiction"=>["Hitch Guide", "P and P"],
  #    "british"=>["Hitch Guide", "P and P"],
  #    "morality"=>["P and P", "Searchin'"],
  #    "non-fiction"=>["Searchin'", "Crazy Ben"],
  #    "gps"=>["Searchin'"],
  #    "dads"=>["Crazy Ben"]}
库=[
{标题:“搭便车指南”,作者:“道格”,猫:[“喜剧”、“小说”、“英国”]},
{标题:“P和P”,作者:“简”,猫:[“道德”、“小说”、“英国”]},
{标题:“搜索”,作者:“乍得”,猫:[“非小说”、“道德”、“全球定位系统”]},
{标题:“疯狂的本”,作者:“沃尔特”,猫:[“非小说”、“喜剧”、“爸爸”]}
]
#=>[{:title=>“搭便车指南”、:by=>“道格”、:cats=>[“喜剧”、“小说”、“英国”],
#{:title=>“P和P”,:by=>“Jane”,:cats=>[“道德”、“小说”、“英国”],
#{:title=>“Searchin'”,:by=>“Chad”,:cats=>[“非小说”、“道德”、“全球定位系统”]},
#{:title=>“疯狂的本”、:by=>“沃尔特”、:cats=>[“非小说”、“喜剧”、“爸爸”]}]
库。每个带有_对象({})do | g,h的|
title=g[:title]
g[:猫]。每只{| c |(h[c]| |=[]){“喜剧”=>[“搭车指南”,“疯狂本”],
#“小说”=>[“挂接指南”,“P和P”],
#“英国”=>[“挂接装置指南”,“P和P”],
#“道德”=>[“P和P”,“搜索],
#“非小说”=>[“搜索”,“疯狂本”],
#“gps”=>[“搜索””,
#“爸爸”=>[“疯狂的本”]}

这是我通常的做法,我认为这是最简单的方法,尽管上面看到的每个带有对象的技巧也很简洁

new_hash = {}

library.each do |hash| 
  hash["categories"].each do |category|
    new_hash[category] ||= []
    new_hash[category] << hash["title"]
  end
end
new_hash={}
library.each do|hash|
散列[“类别”]。每个都做|类别|
新的_散列[类别]| |=[]

new_hash[category]这是我通常的做法,我认为这是最简单的方法,尽管上面看到的每个_with_object技巧也很简洁

new_hash = {}

library.each do |hash| 
  hash["categories"].each do |category|
    new_hash[category] ||= []
    new_hash[category] << hash["title"]
  end
end
new_hash={}
library.each do|hash|
散列[“类别”]。每个都做|类别|
新的_散列[类别]| |=[]
新的[category]您需要澄清(通过编辑)您所说的“…以类别作为元素…”是什么意思。首先,您指的是“键”而不是“元素”。您将看到并非所有答案都以相同的方式进行解释。到目前为止,有一个答案假设“categories”是与键关联的值
“categories”
的元素(散列)中;有两个答案假设“categories”是
元素中“categories”的一个或多个值中包含的字符串(“喜剧”、“小说”、“英国”、“道德”、“社会”等)。我猜您是有意进行后一种解释的。您需要澄清(编辑)您所说的“…以类别作为元素…”是什么意思?首先,您指的是“键”而不是“元素”。您将看到并非所有答案都以相同的方式解释。到目前为止,有一个答案假设“类别”是与元素(哈希)中的键
“类别”
关联的值对于
;两个答案假设“categories”是
元素(“喜剧”、“小说”、“英国”、“道德”、“社会”)中“categories”的一个或多个值中包含的字符串