Cute Ruby trick: split a hash into two hashes with a block

Posted in code, ruby by mtjhax on June 21, 2013
foo = { 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4 }
bar = {|k, v| foo.delete(k) || true if k >= 'c' }
# foo == {"a"=>1, "b"=>2}
# bar == {"c"=>3, "d"=>4}

So why use || true? Consider this example:

foo = { 'a' => 1, 'b' => 2, 'c' => nil, 'd' => 4 }
bar = {|k, v| foo.delete(k) if k >= 'c' }
# foo == {"a"=>1, "b"=>2}
# bar == {"d"=>4}

foo.delete(k) returns the value that was deleted, which in the case of key ‘c’ is the value nil. The Hash#select method treats nil as meaning do not select this element for the result set, so the ‘c’ entry is deleted from the original hash and not included in the result hash. Adding || true returns true even if the value in question evaluates to false or nil.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: