如何正确地将一个散列合并到另一个散列中,替换第一个键。回报率

How to correctly merge one hash into another, replacing the first key. RoR

我目前正在尝试合并两个散列,我真的没有太多其他事情要做,但这就是我需要的结果显示在这个例子中;

{key_1: 'i want to replace this', key_2: 'i want to keep this'}.merge({key_1: 'new text'})

=> {key_1: 'new text', key_2: 'i want to keep this'}

目前我得到的是这样的;
@notification.attributes.merge({body: ()}).to_json 我正在尝试将替换第一个键与 body 元素合并。我真正缺少的是执行密钥替换的参数。如果有人有任何指导、建议甚至答案,将不胜感激,谢谢。

你必须补充!在您的合并操作中,当您进行操作时,它不会影响您的实际对象,但会创建新对象。所以你的例子就像你说的那样我做了以下改变值

{key_1: 'i want to replace this', key_2: 'i want to keep this'}.merge!({key_1: 'new text'})

# result
{:key_1=>"new text", :key_2=>"i want to keep this"}

请更改以下来自

@notification.attributes.merge({body: ()}).to_json

@notification.attributes.merge!({body: ()}).to_json

在 Rails #attributes returns 一个带有字符串键的散列中:

irb(main):001:0> note = Notification.new(title: 'All your base are belong to us', body: 'Loren Ipsum...')
irb(main):002:0> note.attributes
=> {"id"=>nil, "title"=>"All your base are belong to us", "body"=>"Loren Ipsum...", "read_at"=>nil, "created_at"=>nil, "updated_at"=>nil}

如果您想替换散列中的键,您需要使用带有字符串键的散列:

irb(main):003:0> note.attributes.merge("body" => "Moahahahahahaha")
=> {"id"=>nil, "title"=>"All your base are belong to us", "body"=>"Moahahahahahaha", "read_at"=>nil, "created_at"=>nil, "updated_at"=>nil}

或者您需要将散列的键更改为符号,这可以通过 Hash#symbolize_keys:

irb(main):004:0> note.attributes.symbolize_keys.merge(body: "Moahahahahahaha")
=> {:id=>nil, :title=>"All your base are belong to us", :body=>"Moahahahahahaha", :read_at=>nil, :created_at=>nil, :updated_at=>nil}

对于新开发人员来说,这是一个非常常见的错误来源,因为 Rails 通过使用 ActiveSupport::HashWithIndifferentAccess or hash like objects like ActionController::Parameters 在许多地方抽象出符号键和字符串键之间的区别,而 Ruby 本身对区别是严格的。

irb(main):008:0> { "foo" => "bar" }.merge(foo: 'baz')
=> {"foo"=>"bar", :foo=>"baz"}
irb(main):009:0> { "foo" => "bar" }.with_indifferent_access.merge(foo: 'baz')
=> {"foo"=>"baz"}

如果您需要使用嵌套哈希执行此操作,您可以使用递归版本 deep_symbolize_keys and deep_merge

请尝试更改master hash的顺序(master就是你要保留的)

    [9] pry(main)> a = {:key_1=>"i want to replace this", :key_2=>"i want to keep this"}
    => {:key_1=>"i want to replace this", :key_2=>"i want to keep this"}
    
    [10] pry(main)> b = {:key_1=>"new text"}
    => {:key_1=>"new text"}
    
    [11] pry(main)> c = b.merge(a)
     => {:key_1=>"i want to replace this", :key_2=>"i want to keep this"}
    
    [12] pry(main)> d = a.merge(b); // <===== This is what you want.
    => {:key_1=>"new text", :key_2=>"i want to keep this"}

希望对您有所帮助。谢谢