Open In App

How to convert Hash to Object in Ruby?

In this article, we will discuss how to convert a hash to an object in Ruby. Converting hash to an object allows one to access hash keys as object attributes, providing them with a more intuitive way to work with data.

Using OpenStruct

OpenStruct is a Ruby standard library that provides a data structure similar to a Hash but with the ability to access keys as attributes.

Syntax:

require 'ostruct'

object = OpenStruct.new(hash)

Example:

In this example, we create an OpenStruct object person from a hash containing information about a person. We can then access the attributes of the person object using dot notation, making the code more readable.

require 'ostruct'

# Hash containing person information
person_hash = { name: 'John', age: 30, city: 'New York' }

# Convert hash to object using OpenStruct
person = OpenStruct.new(person_hash)

# Accessing attributes of the object
puts "Name: #{person.name}"   
puts "Age: #{person.age}"     
puts "City: #{person.city}"   

Output
Name: John
Age: 30
City: New York

Using Struct

Struct is a built-in Ruby class that allows you to create a new class with specified attributes.

Syntax:

ClassName = Struct.new(:attribute1, :attribute2, ...)

object = ClassName.new(hash[:key1], hash[:key2], ...)

Example: 

In this example we define a Struct class Person with attributes name, age, and city. Then, we create a new object person from the hash containing person information, passing each value as an argument.

# Define a Struct class with attributes
Person = Struct.new(:name, :age, :city)

# Hash containing person information
person_hash = { name: 'John', age: 30, city: 'New York' }

# Convert hash to object using Struct
person = Person.new(*person_hash.values)

# Accessing attributes of the object
puts "Name: #{person.name}"   
puts "Age: #{person.age}"    
puts "City: #{person.city}"   

Output
Name: John
Age: 30
City: New York

Using Hash#each

Hash#each method allows to iterates over the hash and dynamically defines attributes for an object

Syntax:

object = Object.new

hash.each { |key, value| object.define_singleton_method(key) { value } }

Example: 

In this example we create a new empty object and iterate over the hash. For each key-value pair in the hash, we dynamically define a method on the object with the key as the method name and the value as the return value.

# Hash containing person information
person_hash = { name: 'John', age: 30, city: 'New York' }

# Create an empty object
person = Object.new

# Define attributes dynamically from hash
person_hash.each { |key, value| person.define_singleton_method(key) { value } }

# Accessing attributes of the object
puts "Name: #{person.name}"   # Output: Name: John
puts "Age: #{person.age}"     # Output: Age: 30
puts "City: #{person.city}"   # Output: City: New York

Output
Name: John
Age: 30
City: New York
Article Tags :