您可以将键设置为 nil 值,如下所示:
h = Hash.new
h["nil_key"] = nil
h.keys # => ["nil_key"]
in your example you could define it like this
def add(key, value = nil)
h = { key => value }
@j.merge!(h)
end
@j = { :a_key => "a_value" }
@j.add("fish")
@j.keys # => [:a_key, "fish"]
@j.add("another_key", "another_value")
@j.keys # => [:a_key, "fish", "another_key"]
@j # => [ :a_key => "a_value", "fish" => nil, "another_key" => "another_value"]
just make sure you define #add in whatever class the @j instance variable is defined in.