---
title: "Rails 5.2 fetch_values for HashWithIndifferentAccess"
description:
  "Starting Rails 5.2 we'll be able to make use of fetch_values
  HashWithIndifferentAccess analogous to its use on Hash."
canonical_url: "https://www.bigbinary.com/blog/rails-5-2-implements-fetch_values-for-hashwithindifferentaccess"
markdown_url: "https://www.bigbinary.com/blog/rails-5-2-implements-fetch_values-for-hashwithindifferentaccess.md"
---

# Rails 5.2 fetch_values for HashWithIndifferentAccess

Starting Rails 5.2 we'll be able to make use of fetch_values
HashWithIndifferentAccess analogous to its use on Hash.

- Author: Mohit Natoo
- Published: December 6, 2017
- Categories: Rails 5.2, Rails

Ruby 2.3 added
[fetch_values method to hash](https://bugs.ruby-lang.org/issues/10017).

By using `fetch_values` we are able to get values for multiple keys in a hash.

```ruby
capitals = { usa: "Washington DC",
             china: "Beijing",
             india: "New Delhi",
             australia: "Canberra" }

capitals.fetch_values(:usa, :india)
#=> ["Washington DC", "New Delhi"]

capitals.fetch_values(:usa, :spain) { |country| "N/A" }
#=> ["Washington DC", "N/A"]
```

Rails 5.2 introduces method `fetch_values`
[on HashWithIndifferentAccess](https://github.com/rails/rails/pull/28316). We'll
hence be able to fetch values of multiple keys on any instance of
HashWithIndifferentAccess class.

```ruby
capitals = HashWithIndifferentAccess.new
capitals[:usa] = "Washington DC"
capitals[:china] = "Beijing"

capitals.fetch_values("usa", "china")
#=> ["Washington DC", "Beijing"]

capitals.fetch_values("usa", "spain") { |country| "N/A" }
#=> ["Washington DC", "N/A"]
```

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5-2-implements-fetch_values-for-hashwithindifferentaccess)
