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.
# 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
Contact Us