Ease Access of Hash Values

01 January 2015

Accessing hash values in Ruby can be done in multiple ways. Let's explore the most efficient and elegant approaches.

Traditional Approach

user = { name: "John", email: "john@example.com" }
puts user[:name]
# => "John"

Using dig Method (Ruby 2.3+)

address = { home: { city: "Bangalore", zip: "560001" } }
city = address.dig(:home, :city)
# => "Bangalore"

# Safe for nil values
state = address.dig(:home, :state)
# => nil (no error)

Using Fetch Method

user = { name: "John" }
age = user.fetch(:age, 25)  # Default value
# => 25

Using Transform Keys

hash = { "name" => "John", "email" => "john@example.com" }
hash.transform_keys(&:to_sym)
# => { name: "John", email: "john@example.com" }

Each method has its use case depending on your needs.

← Back to Blog

About the Author

Kameshwaran Sachithanantham

Software Engineer cum Project Manager with 11+ years of experience in React, Node.js, React Native, and Ruby on Rails.