Back to Blog

Rails 5.2 fetch_values for HashWithIndifferentAccess

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"]

You might also like

If you liked this blog post, check out similar ones from BigBinary