0

I am using Ruby on Rails 3.2.2 and I am looking for a method which is the opposite of except for hashes (except documentation), probably an only method. Is there some method or an easy way so that I can return a hash that includes only the given keys?

# Example, 'only' method as opposite to the 'except'
@person.update_attributes(params[:person].only(:name, :surname))
user12882
  • 4,702
  • 9
  • 39
  • 54
  • See also [Slicing Params Hash for Specific Values](http://stackoverflow.com/questions/5652976/slicing-params-hash-for-specific-values). – Phrogz May 11 '12 at 21:56

1 Answers1

2

I think what you are looking for is slice, which will return a hash with only the given keys.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
GorrillaMcD
  • 1,884
  • 1
  • 14
  • 22
  • @GorrillaMcD - The Ruby on Rails team should continue to use the "common" `except/only` pair instead of `except/slice`! It can confuse a lot of people. – user12882 May 11 '12 at 22:06
  • I tried googling for confirmation on this, but couldn't find anything. However, I think "only" is already used elsewhere in Ruby on Rails, so they had to pick a different name for the method. – GorrillaMcD May 11 '12 at 23:34