BigBinary Blog

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

Rails 5.2 fetch_values for HashWithIndifferentAccess

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.

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. We'll hence be able to fetch values of multiple keys on any instance of HashWithIndifferentAccess class.

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"]
Mohit Natoo in Rails 5.2
06, 2017
Share

You might also like

Recyclable cache keys in Rails

Rails 5.2 DSL for configuring Content Security Policy

Rails 5.2 stops some raw SQL, prevents SQL injections

Rails 5.2 added method write_multi to cache store

Rails 5.2 uses AES-256-GCM authenticated encryption

Subscribe to our newsletter