Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: a simpler Hash.slice method?

In http://api.rubyonrails.org/classes/Hash.html#method-i-slice, I see

valid_keys = [:mass, :velocity, :time]
search(options.slice(*valid_keys))

I don't get the usage here. I mean, if I pass an array into slice, I definitely want every key get sliced, then why use an addtional * here?

Is is possible to make it into something like:

valid_keys = [:mass, :velocity, :time]
search(options.simple_slice(valid_keys))

by creating a simpler version of slice?

like image 919
cqcn1991 Avatar asked Oct 26 '25 11:10

cqcn1991


1 Answers

Hashes can have all sorts of things for keys, the keys don't have to be just strings or symbols. For example, this is a perfectly valid Hash:

{ [ :mass, :velocity, :time ] => 'pancakes' }

How is Hash#slice supposed to know that sometimes this:

h.slice([:mass, :velocity, :time])

means "give me the sub-hash with those three keys" and sometimes it means "give me the sub-hash with that array as a key"?

Hash#slice takes a list of keys (one key per argument) so if you want to have your keys in an array then you have to splat them into individual arguments:

h.slice(*some_array_of_keys)
# ------^ expand the array into individual arguments

That's why you need the *.

If you want to assume that the keys will never be arrays then you're free to say something like:

def simple_slice(*keys) # Allow any number of arguments
  slice(*keys.flatten)  # flatten all the arrays and then punt to Rails's slice.
end

You might not want to flatten only one level (or maybe you don't).

like image 69
mu is too short Avatar answered Oct 29 '25 03:10

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!