【问题标题】:Add hash argument or string argument in a method to a hash (Ruby)将方法中的哈希参数或字符串参数添加到哈希(Ruby)
【发布时间】:2015-05-27 16:26:16
【问题描述】:

如果 add 方法的参数“entry”是一个散列,我需要将它添加到 :entries 散列。如果“entry”是一个字符串,则需要将“entry”设置为哈希中的键,并将其值设置为 nil。我在下面有一个解决方案,但有更清洁的方法吗?

class Test
    attr_accessor :entries

    def initialize
        @entries = {}
    end

    def add(entry)
        if entry.is_a?(Hash)
          entry.each do |word, definition|
            @entries[word] = definition
          end
        else
          @entries[entry] = nil
        end
    end
end

@test = Test.new
@test.add("the")
#{"the" => nil}
@test.add("the" => "one")
#{"the"=>"one"}

【问题讨论】:

  • 也许你可以将“@entries”设置为Hash.new(nil),这样@entries的任意key的值都是nil,那么你添加entry就判断entry是否为Hash,并合并它

标签: ruby methods hash arguments


【解决方案1】:

我重构了代码:

class Test
  attr_accessor :entries

  def initialize
    @entries = {}
  end

  def add(entry)
    entry.is_a?(Hash) ? @entries.merge!(entry) : @entries[entry] = nil
  end
end

【讨论】:

    猜你喜欢
    • 2011-09-18
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2014-12-09
    • 2017-10-28
    • 2012-09-03
    • 2016-09-06
    • 2012-05-28
    相关资源
    最近更新 更多