【问题标题】:Merging hashes in Ruby not working as intended在 Ruby 中合并哈希未按预期工作
【发布时间】:2016-04-21 15:21:57
【问题描述】:

我正在尝试在合并两个哈希的 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 的屏幕截图)。但是,如果正确执行“资本”和“更多资本”哈希的合并,我也希望输出包含“奥斯汀是德克萨斯州的首府”和“费尔班克斯是阿拉斯加的首府”。为什么不是这样?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您正在使用merge 的非破坏性版本,它返回一个您需要分配和使用的新哈希。

    new_capitals = capitals.merge(more_capitals)
    

    或者,您可以使用merge!,它可以做到这一点:

    capitals.merge!(more_capitals)
    

    【讨论】:

    • 为了澄清这些术语,这里的“非破坏性”是指“制作一个副本”,与使用! 的就地修改版本相比。
    【解决方案2】:

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

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

     > capitals      = { 'New York' => 'Albany', 'California' => 'Sacramento'}
     > more_capitals = {:'New York' => 'Albany', '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
    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 2022-10-24
      • 2011-07-31
      • 2021-06-30
      • 1970-01-01
      • 2012-01-14
      • 2019-02-21
      相关资源
      最近更新 更多