dansch
dansch

Reputation: 6267

Underscore's pick method in ruby

I'd like to use something like

hash.pick('prop1', 'prop2')

the same way as using underscores pick method ( takes properties of an object/hash and create a new hash based on them )

So it will look like this

{ prop1: 'asdf', prop2: 'qwer', prop3: 'uiop' }.pick( 'prop2', 'prop3' )
# equals { prop2: 'qwer', prop3: 'uiop' }

Upvotes: 5

Views: 2501

Answers (2)

Simon Perepelitsa
Simon Perepelitsa

Reputation: 20639

For Ruby 2.5 and later, use the built-in hash.slice method.

{ prop1: 'asdf', prop2: 'qwer', prop3: 'uiop' }.slice(:prop2, :prop3)

This method was first introduced in Rails (ActiveSupport), so it was usable in earlier Ruby versions within Rails environment.

Upvotes: 7

Erez Rabih
Erez Rabih

Reputation: 15788

Use Hash slice method as in:

hash.slice(:prop1, :prop2)

Upvotes: 9

Related Questions