How to build a Ruby hash out of two equally-sized

2019-01-30 00:35发布

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?

标签: ruby arrays hash
3条回答
啃猪蹄的小仙女
2楼-- · 2019-01-30 00:49
h = Hash[a.zip b] # => {:baz=>1, :bof=>2, :bar=>"world", :foo=>"hello"}

...damn, I love Ruby.

查看更多
等我变得足够好
3楼-- · 2019-01-30 00:52

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!

查看更多
走好不送
4楼-- · 2019-01-30 01:03

How about this one?

[a, b].transpose.to_h

If you use 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.

查看更多
登录 后发表回答