How to use Struct In Ruby

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.

Ruby
# 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

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.

Table of Content

  • Using OpenStruct
  • Using Struct
  • Using Hash#each

Similar Reads

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....

Using Struct

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

Using Hash#each

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

Contact Us