This blog is part of our Ruby 2.5 series.
Let's say we have a hash
{ id: 1, name: 'Ruby 2.5', description: 'BigBinary Blog' } and we want to
select key value pairs having the keys name and description.
We can use the Hash#select method.
irb> blog = { id: 1, name: 'Ruby 2.5', description: 'BigBinary Blog' }
=> {:id=>1, :name=>"Ruby 2.5", :description=>"BigBinary Blog"}
irb> blog.select { |key, value| [:name, :description].include?(key) }
=> {:name=>"Ruby 2.5", :description=>"BigBinary Blog"}
Matzbara Masanao proposed a simple method to take care of this problem.
Some of the names proposed were choice and pick.
Matz suggested the name slice since this
method is ActiveSupport compatible.
irb> blog = { id: 1, name: 'Ruby 2.5', description: 'BigBinary Blog' }
=> {:id=>1, :name=>"Ruby 2.5", :description=>"BigBinary Blog"}
irb> blog.slice(:name, :description)
=> {:name=>"Ruby 2.5", :description=>"BigBinary Blog"}
So, now we can use a simple method slice to select key value pairs from a hash
with specified keys.
Here is the relevant commit and discussion.

Written byAmit Choudhary
Related blogs
- 01Ruby 2.5 added lazy proc allocation for block parametersMay 22, 2018 · Amit Choudhary
- 02Ruby 2.5 adds Thread.report_on_exception by defaultApril 18, 2018 · Vishal Telangre
- 03Ruby 2.5 adds Exception#full_message methodMarch 13, 2018 · Vishal Telangre
- 04Ruby 2.5 prints backtrace & error message in reverseMarch 7, 2018 · Vishal Telangre