Ruby结合哈希?

时间:2015-11-24 15:30:12

标签: ruby

ruby​​中是否有方法将两个哈希合并为一个?具体来说,我想要A = {:a => :b}B = {:b => :c}

AB = combine(A,B)
=> {:a => :c}

如果ruby的标准库中没有一个,我可以创建自己的,但我宁愿不重新发明轮子。

1 个答案:

答案 0 :(得分:1)

a = {:a => :b}
b = {:b => :c}

# Works on ruby >= 2.1
c = a.map{|k, v| [k, b[v]]}.to_h  #=> {:a => :c}

# Works on all versions of ruby
c = Hash[a.map{|k, v| [k, b[v]]}]  #=> {:a => :c}