How to merge Ruby hashes

前端 未结 4 982
我寻月下人不归
我寻月下人不归 2020-11-28 08:45

How can I merge these two hashes:

{:car => {:color => \"red\"}}
{:car => {:speed => \"100mph\"}}

To get:

{:car          


        
4条回答
  •  隐瞒了意图╮
    2020-11-28 09:15

    You can use the merge method defined in the ruby library. https://ruby-doc.org/core-2.2.0/Hash.html#method-i-merge


    Example

    h1={"a"=>1,"b"=>2} 
    h2={"b"=>3,"c"=>3} 
    h1.merge!(h2)
    

    It will give you output like this {"a"=>1,"b"=>3,"c"=>3}

    Merge method does not allow duplicate key, so key b will be overwritten from 2 to 3.

    To overcome the above problem, you can hack merge method like this.

    h1.merge(h2){|k,v1,v2|[v1,v2]}
    

    The above code snippet will be give you output

    {"a"=>1,"b"=>[2,3],"c"=>3}
    

提交回复
热议问题