谁能帮我理解 map 函数在这段代码中的作用?
counts = @a.group_by{|i| i}.map{|k,v| [k[0], k[1], v.count]}
最佳答案
@a.group_by{|i| i}
正在生成一个散列,其中 key/value 对是 Array
。
现在 #map
方法获取每一对。 k
是一个键
,v
是一个值,在map
中创建一个数组[first_entry_of_array, second_entry_of_array,value_array_size]
(当键/值都是数组时)。我说过 key
可以是数组,因为您使用了 k[0]
、k[1]
和 Array#[]
。是实际的方法。
示例:
a = [ %w(foo bar) ,%W(baz bar), %w(foo bar) ]
a.group_by { |e| e }
# => {["foo", "bar"]=>[["foo", "bar"], ["foo", "bar"]],
# ["baz", "bar"]=>[["baz", "bar"]]}
a.group_by { |e| e }.map{|k,v| [k[0], k[1], v.count]}
# => [["foo", "bar", 2], ["baz", "bar", 1]]
key
也可以是一个string。然后它在 #map
内部将是 [first_character_of_string,second_character_of_string,value_array_size]
。与 with 相同的原因,我怀疑 key
可以是一个字符串,因为这些调用是 String#[]
方法调用。
示例:
a = %w(foo bar foo baz bar)
a.group_by { |e| e }
# => {"foo"=>["foo", "foo"], "bar"=>["bar", "bar"], "baz"=>["baz"]}
# ^ ^
# key value
a.group_by { |e| e }.map{|k,v| [k[0], k[1], v.count]}
# => [["f", "o", 2], ["b", "a", 2], ["b", "a", 1]]
基本上 #map
会在这里生成一个数组的数组。
直接来自 map
的文档:
Returns a new array with the results of running block once for every element in enum.
在您的示例中,带有运行 block 的结果,意味着在每次迭代后从带有 #map
的 block 生成结果,是 [ k[0], k[1], v.count]
.
直接来自 group_by
的文档:
Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key.
希望对您有所帮助!
关于数组中的 Ruby map 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21741914/