将方法中的散列参数或字符串参数添加到散列 (Ruby)
Add hash argument or string argument in a method to a hash (Ruby)
如果方法 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"}
我重构了代码:
class Test
attr_accessor :entries
def initialize
@entries = {}
end
def add(entry)
entry.is_a?(Hash) ? @entries.merge!(entry) : @entries[entry] = nil
end
end
如果方法 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"}
我重构了代码:
class Test
attr_accessor :entries
def initialize
@entries = {}
end
def add(entry)
entry.is_a?(Hash) ? @entries.merge!(entry) : @entries[entry] = nil
end
end