Ruby 2.5 added Hash#slice method

Amit Choudhary

By Amit Choudhary

on February 6, 2018

This blog is part of our  Ruby 2.5 series.

Ruby 2.4

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.

1irb> blog = { id: 1, name: 'Ruby 2.5', description: 'BigBinary Blog' }
2  => {:id=>1, :name=>"Ruby 2.5", :description=>"BigBinary Blog"}
3
4irb> blog.select { |key, value| [:name, :description].include?(key) }
5  => {: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.

Ruby 2.5.0

1irb> blog = { id: 1, name: 'Ruby 2.5', description: 'BigBinary Blog' }
2  => {:id=>1, :name=>"Ruby 2.5", :description=>"BigBinary Blog"}
3
4irb> blog.slice(:name, :description)
5  => {: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.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.