0

我想知道是否有更优雅的方式来编写以下行:

section_event_hash = []
sections.each do |s|
   section_event_hash << { s => s.find_all_events }
end

我想创建一个哈希,其键是 的元素,值是该方法sections返回的元素数组。find_all_events

4

3 回答 3

3

如果你想section_event_hash真正成为一个哈希而不是一个数组,那么你可以使用each_with_object

section_event_hash = sections.each_with_object({}) { |s, h| h[s] = s.find_all_events }

您可以使用map构建一个数组数组,然后将其提供给Hash[]

section_event_hash = Hash[sections.map { |s| [s, s.find_all_events] }]
于 2012-11-21T05:20:26.013 回答
1

您发布的代码并没有完全按照您所说的去做。让我们通过这样的测试来仔细看看它:

sections = ["ab", "12"]

section_event_hash = []
sections.each do |s|
   section_event_hash << { s => s.split("") }
end

puts section_event_hash.inspect

给出:

[{"ab"=>["a", "b"]}, {"12"=>["1", "2"]}]

因此,您实际上创建了一个哈希数组,其中每个哈希包含一个键值对。

以下代码生成一个包含多个元素的哈希。请注意如何使用 {} 而不是 [] 创建空哈希。花括号是哈希的符号,而方括号指的是特定的键。

section_event_hash = {}
sections.each do |s|
   section_event_hash[s] = s.split("")
end

puts section_event_hash.inspect

=>{"ab"=>["a", "b"], "12"=>["1", "2"]}

至于“更优雅”的方式,这取决于您的定义。正如此处的其他答案所表明的那样,通常有不止一种方法可以在 ruby​​ 中做某事。seph 产生与原始代码相同的数据结构,而 mu 产生您描述的哈希。就个人而言,我的目标只是易于阅读、理解和维护的代码。

于 2012-11-21T06:38:33.480 回答
0
array_of_section_event_hashes = sections.map do |s|
  {s => s.find_all_events}
end
于 2012-11-21T05:21:15.417 回答