ruby中是否有方法将两个哈希合并为一个?具体来说,我想要A = {:a => :b}
和B = {:b => :c}
AB = combine(A,B)
=> {:a => :c}
如果ruby的标准库中没有一个,我可以创建自己的,但我宁愿不重新发明轮子。
答案 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}