Rails 5.2 fetch_values for HashWithIndifferentAccess

Mohit Natoo

By Mohit Natoo

on December 6, 2017

This blog is part of our  Rails 5.2 series.

Ruby 2.3 added fetch_values method to hash.

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

1capitals = { usa: "Washington DC",
2             china: "Beijing",
3             india: "New Delhi",
4             australia: "Canberra" }
5
6capitals.fetch_values(:usa, :india)
7#=> ["Washington DC", "New Delhi"]
8
9capitals.fetch_values(:usa, :spain) { |country| "N/A" }
10#=> ["Washington DC", "N/A"]

Rails 5.2 introduces method fetch_values on HashWithIndifferentAccess. We'll hence be able to fetch values of multiple keys on any instance of HashWithIndifferentAccess class.

1capitals = HashWithIndifferentAccess.new
2capitals[:usa] = "Washington DC"
3capitals[:china] = "Beijing"
4
5capitals.fetch_values("usa", "china")
6#=> ["Washington DC", "Beijing"]
7
8capitals.fetch_values("usa", "spain") { |country| "N/A" }
9#=> ["Washington DC", "N/A"]

If you liked this blog, you might also like the other blogs we have written. Check out the full archive.

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

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