---
title: "Ruby 2.5 added Hash#slice method"
description: "Hash#slice method is added in Ruby 2.5"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-5-added-hash-slice-method"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-5-added-hash-slice-method.md"
---

# Ruby 2.5 added Hash#slice method

Hash#slice method is added in Ruby 2.5

- Author: Amit Choudhary
- Published: February 6, 2018
- Categories: Ruby 2.5, Ruby

#### 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](https://ruby-doc.org/core-2.4.2/Hash.html#method-i-select) method.

```ruby
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](https://bugs.ruby-lang.org/users/5184) proposed a simple
method to take care of this problem.

Some of the names proposed were `choice` and `pick`.

[Matz](https://twitter.com/yukihiro_matz) suggested the name `slice` since this
method is ActiveSupport compatible.

#### Ruby 2.5.0

```ruby
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](https://github.com/ruby/ruby/commit/6c50bdda0b)
and [discussion](https://bugs.ruby-lang.org/issues/13563).

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-5-added-hash-slice-method)
