没有(Ruby缺乏将Enumerables变为Hashes的方法),但编写自己的方法非常简单:
module Enumerable def hash_with each_with_object({}) {|elm, hsh| hsh[elm] = yield(elm) } end end [1,2,3].hash_with {|n| n + 3 } # => { 1 => 4, 2 => 5, 3 => 6 } ('a'..'e').hash_with(&:upcase) # => { "a" => "A", "b" => "B", "c" => "C", "d" => "D", "e" => "E" } (:A..:E).hash_with { rand 100 } # => { A: 28, B: 67, C: 58, D: 12, E: 20}
看看each_with_object
.
文档的示例:
evens = (1..10).each_with_object([]) { |i, a| a << i*2 } #=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
在该示例中,他们使用的是数组,[]
但您可以轻松地使用哈希{}
并将内容填充到其中:
hash = [1,2,3].each_with_object({}) { |i, h| h[i] = i + 3 } # => {1=>4, 2=>5, 3=>6}