How to use OpenStruct In Ruby

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.

Ruby
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

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