转换这个数组:

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

...到哈希值:

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

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


当前回答

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

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

其他回答

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

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

只用哈希。[]与数组中的值。例如:

arr = [1,2,3,4]
Hash[*arr] #=> gives {1 => 2, 3 => 4}

你可以这样尝试,对于单个数组

irb(main):019:0> a = ["item 1", "item 2", "item 3", "item 4"]
  => ["item 1", "item 2", "item 3", "item 4"]
irb(main):020:0> Hash[*a]
  => {"item 1"=>"item 2", "item 3"=>"item 4"}

对于数组的数组

irb(main):022:0> a = [[1, 2], [3, 4]]
  => [[1, 2], [3, 4]]
irb(main):023:0> Hash[*a.flatten]
  => {1=>2, 3=>4}

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

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

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}