转换这个数组:

a = ["item 1", "item 2", "item 3", "item 4"] 

...到哈希值:

{ "item 1" => "item 2", "item 3" => "item 4" }

例如,偶数下标处的元素是键,奇数下标处的元素是值。


当前回答

枚举器包括Enumerable。从2.1开始,Enumerable也有一个方法#to_h。这就是为什么,我们可以写:-

a = ["item 1", "item 2", "item 3", "item 4"]
a.each_slice(2).to_h
# => {"item 1"=>"item 2", "item 3"=>"item 4"}

因为没有block的#each_slice给了我们Enumerator,并且根据上面的解释,我们可以在Enumerator对象上调用#to_h方法。

其他回答

Ruby 2.1.0在Array上引入了to_h方法,如果原始数组由键-值对数组组成,则该方法可以满足您的需求:http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-to_h。

[[:foo, :bar], [1, 2]].to_h
# => {:foo => :bar, 1 => 2}
a = ["item 1", "item 2", "item 3", "item 4"]
Hash[ a.each_slice( 2 ).map { |e| e } ]

或者,如果你讨厌Hash[…]]:

a.each_slice( 2 ).each_with_object Hash.new do |(k, v), h| h[k] = v end

或者,如果你是坏函数式编程的懒粉丝:

h = a.lazy.each_slice( 2 ).tap { |a|
  break Hash.new { |h, k| h[k] = a.find { |e, _| e == k }[1] }
}
#=> {}
h["item 1"] #=> "item 2"
h["item 3"] #=> "item 4"

这就是我在谷歌上搜索这个的时候想要的:

[{a: 1}, {b: 2}].reduce({}) {|h, v| h.merge v} => {:a=>1,:b=>2}

枚举器包括Enumerable。从2.1开始,Enumerable也有一个方法#to_h。这就是为什么,我们可以写:-

a = ["item 1", "item 2", "item 3", "item 4"]
a.each_slice(2).to_h
# => {"item 1"=>"item 2", "item 3"=>"item 4"}

因为没有block的#each_slice给了我们Enumerator,并且根据上面的解释,我们可以在Enumerator对象上调用#to_h方法。

或者如果你有一个[key, value]数组,你可以这样做:

[[1, 2], [3, 4]].inject({}) do |r, s|
  r.merge!({s[0] => s[1]})
end # => { 1 => 2, 3 => 4 }