Here are some potentiall useful one-liner methods for extracting and merging only parts of Hashes. I was surprised to find out that Hash didn't already have built-in methods to do these things. Maybe they're considered so obvious that they don't need to be built-in, but I think the readability gain is worth it.
Comments
Daniel Neissaid on
Hello Jacius!!!
Really good one liners.
But why don't do with_only like this:
def with_only( *keys ) select{ |k,v| keys.include?(k) } end
I guess reject + not is the same as select....
See ya
John Croisantsaid on
That was my first thought as well. But strangely, Hash#select doesn't return a Hash, it returns nested arrays, like [[:a, 1], [:b, 2]]. So, using reject turned out to be the simplest way.
Comments
on
Hello Jacius!!!
Really good one liners.
But why don't do with_only like this:
I guess reject + not is the same as select....
See ya
on
That was my first thought as well. But strangely, Hash#select doesn't return a Hash, it returns nested arrays, like
[[:a, 1], [:b, 2]]
. So, using reject turned out to be the simplest way.Comments are closed.