I have two arrays
我有两个数组
a = [:foo, :bar, :baz, :bof]
and
和
b = ["hello", "world", 1, 2]
I want
我想要的
{:foo => "hello", :bar => "world", :baz => 1, :bof => 2}
Any way to do this?
有什么办法吗?
3 个解决方案
#1
174
h = Hash[a.zip b] # => {:baz=>1, :bof=>2, :bar=>"world", :foo=>"hello"}
...damn, I love Ruby.
…该死,我爱Ruby。
#2
27
Just wanted to point out that there's a slightly cleaner way of doing this:
我想指出的是,有一种更清洁的方法:
h = a.zip(b).to_h # => {:foo=>"hello", :bar=>"world", :baz=>1, :bof=>2}
Have to agree on the "I love Ruby" part though!
但是我必须同意“我爱Ruby”这部分!
#3
13
How about this one?
这一个怎么样?
[a, b].transpose.to_h
If you use Ruby 1.9:
如果你使用Ruby 1.9:
Hash[ [a, b].transpose ]
I feel a.zip(b)
looks like a
is master and b
is slave, but in this style they are flat.
我觉得a.zip(b)看起来a是master, b是slave,但在这种风格下,它们是扁平的。
#1
174
h = Hash[a.zip b] # => {:baz=>1, :bof=>2, :bar=>"world", :foo=>"hello"}
...damn, I love Ruby.
…该死,我爱Ruby。
#2
27
Just wanted to point out that there's a slightly cleaner way of doing this:
我想指出的是,有一种更清洁的方法:
h = a.zip(b).to_h # => {:foo=>"hello", :bar=>"world", :baz=>1, :bof=>2}
Have to agree on the "I love Ruby" part though!
但是我必须同意“我爱Ruby”这部分!
#3
13
How about this one?
这一个怎么样?
[a, b].transpose.to_h
If you use Ruby 1.9:
如果你使用Ruby 1.9:
Hash[ [a, b].transpose ]
I feel a.zip(b)
looks like a
is master and b
is slave, but in this style they are flat.
我觉得a.zip(b)看起来a是master, b是slave,但在这种风格下,它们是扁平的。