Ruby哈希直接访问与合并

kiayqfof  于 2023-04-05  发布在  Ruby
关注(0)|答案(4)|浏览(122)

以下两者之间是否存在差异:

@attr[:field] = new_value

@attr.merge(:field => new_value)
qq24tv8q

qq24tv8q1#

如果您使用merge!而不是merge,则没有区别。
唯一的区别是您可以使用多个字段(即:另一散列)。
示例:

h1 = { "a" => 100, "b" => 200 }
   h2 = { "b" => 254, "c" => 300 }
   h3 = h1.merge(h2)    
   puts h1         # => {"a" => 100, "b" => 200}
   puts h3         # => {"a"=>100, "b"=>254, "c"=>300}
   h1.merge!(h2)   
   puts h1         # => {"a"=>100, "b"=>254, "c"=>300}

当分配单个值时,出于可读性原因,我更喜欢h[:field] = new_val而不是merge,并且我猜它比合并更快。
你也可以看看Hash-rdoc:http://ruby-doc.org/core/classes/Hash.html#M000759

vsnjm48y

vsnjm48y2#

但是,他们做同样的事情:

@attr[:field] = new_value

更有效,因为不需要哈希遍历。

ef1yzkbh

ef1yzkbh3#

Merge在不同位置返回新的hash,将other_hashes合并到self中,但**Merge!**的操作类似于“update”返回self hash,在self位置复制。

h1 = { "a": 1 }
    h2 = { "b": 2 }

    def merge_hash (h1,h2)
      puts h1                 # {:a=> 1}
      puts h1.object_id       # 340720
  
      h1 = h1.merge(h2)
      puts h1                 # {:a=>1, :b=>2}
      puts h1.object_id       # 340760
    end

    merge_hash(h1, h2)
    puts h1                     # {:a=>1}
    puts h1.object_id           # 340720

    def merge_hash (h1,h2)
      puts h1                 # {:a=>1}
      puts h1.object_id       # 340720
  
      h1 = h1.merge!(h2)
      puts h1                 # {:a=>1, :b=>2}
      puts h1.object_id       # 340720
    end

    merge_hash(h1, h2)
    puts h1                     # {:a=>1, :b=>2}
    puts h1.object_id           # 340720
muk1a3rh

muk1a3rh4#

您可以使用非bang合并来在函数式编程风格中使用散列。
Ruby Functional Programming中的Don't update variables
不更新哈希
编号:

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

有:

hash = {:a => 1, :b => 2}
new_hash = hash.merge(:c => 3)

相关问题