Reputation: 21
Consider the following hash:
H = {"a" => 100, "b" => 200, "c" => nil, "d" => nil}
I want to preserve the nil
value with "c"
, and remove the nil
value with "d"
. How can I do that?
Applying compact
will remove all nil
values (i.e., with keys "c"
and "d"
).
Question Removing all empty elements from a hash / YAML? addresses this issue, but I thought there could have been a function equivalent to .compact
.
Upvotes: 1
Views: 2354
Reputation: 11
If it is just one key, why not Hash#delete to remove the pair from the Hash instance?
h = {"a" => 100, "b" => 200, "c" => nil, "d" => nil}
h.delete("d")
h # => {"a" => 100, "b" => 200, "c" => nil}
Upvotes: 1
Reputation: 110745
h = Hash["a" => 100, "b" => 200, "c" => nil, "d" => nil]
If the resulting key order is not important you could write:
h.compact.merge("c" => nil)
#=> {"a"=>100, "b"=>200, "c"=>nil}
or
h.compact!.update("c" => nil)
if the hash is to be modified in place.
Upvotes: 1
Reputation: 11193
If I get the point, once you know that a specific key must be nil
, for example "c"
you could do something like:
h = {"a"=>100, "b"=>200, "c"=>nil, "d"=>nil}
h.compact!["c"] = nil
# => {"a"=>100, "b"=>200, "c"=>nil}
Now, if you call h["c"]
you get nil
.
Consider also that when you simply do h.compact!
and call h["c"]
you get nil
anyway.
Upvotes: 0
Reputation: 211720
There's a method for that:
h.delete_if { |k,v| v.nil? }
Where k,v
represents the key/value pair.
If you can quantify why you want the c
key preserved you can incorporate that in the logic. Is it just the first nil
that's saved?
If that's the case, you can try this:
count = 0
h.delete_if { |k,v| v.nil? && (count += 1) != 1 }
Note that Ruby is a case sensitive language and H
is a constant by virtue of being a capital letter. For variables use lower-case only.
Additionally, the traditional way to declare a Ruby hash is:
h = { "a" => 100, "b" => 200, "c" => nil, "d" => nil }
Where that's only if you want string keys. With Symbol keys it's even more concise:
h = { a: 100, b: 200, c: nil, d: nil }
Upvotes: 2