2016-04-21 29 views
0

我想重现合并两个哈希的Ruby教程中的示例。但是,使用“合并”方法不会产生预期的效果。当我运行下面的脚本:在红宝石合并哈希不按预期工作

capitals={'New York' => 'Albany','California' => 'Sacramento'} 
more_capitals={'Texas' => 'Austin', 'Alaska' => 'Fairbanks'} 

capitals.merge(more_capitals) 

capitals.each do |state,capital| 
    puts "#{capital} is the capital of #{state}" 
end 

我得到这样的结果:

Albany is the capital of New York 
Sacramento is the capital of California 

(见截屏来自repl.it下文)。但是,如果合并“首都”和“更多首都”的哈希正确执行,我也会期望输出包含“奥斯汀是德克萨斯州的首府”和“费尔班克斯是阿拉斯加州的首府”。为什么不是这种情况?

enter image description here

回答

6

您使用的merge无损版本,它返回你需要分配并使用新的Hash。

new_capitals = capitals.merge(more_capitals) 

或者,你可以使用merge!,这确实很到位:

capitals.merge!(more_capitals) 
+0

为了阐明这些术语,这里的“非破坏性”意思是“制作一个副本”,而不是就地修改版本,用'!'来表示。 – tadman

1

仅供参考,除了@Kristján's Answer

有时你也可能会遇到这种情况,并得到惊讶

> capitals  = { 'New York' => 'Albany', 'California' => 'Sacramento'} 
> more_capitals = {:'New York' => 'Albany', 'Alaska' => 'Fairbanks'} 
> capitals.merge!(more_capitals) 

and

capitals.each do |state,capital| 
    puts "#{capital} is the capital of #{state}" 
end 

输出

Albany is the capital of New York 
Sacramento is the capital of California 
Albany is the capital of New York 
Fairbanks is the capital of Alaska 

问题

为什么不工作merge!,它应该具有相同的键合并值。即New York

说明:
RubyHashsymbolstringarrayhashInteger和被认为是单独的键。

> new_hash = {:'a' => 'value with string symbol as a key', 'a' => 'value with string as a key', [:a] => 'value with array as a key', {a: 'key_hash'} => 'value with hash a key'} 

    > new_hash[:a] 
=> "value with string symbol as a key" 
    > new_hash['a'] 
=> "value with string as a key" 
    > new_hash[[:a]] 
=> "value with array as a key" 
    > new_hash[{a: 'key_hash'}] 
=> "value with hash a key"