Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing hash attribute the same way as accessing an object attribute

Tags:

ruby

hash

I have a ruby hash, say

h={name: "john", age: "23"}

It is not an object, just a hash created from an object. I want to access its values with the method attribute as I access an object. i.e.:

h.name => "john"
h.age  => 23

Is it possible to do this?

like image 225
sovanlandy Avatar asked Dec 16 '22 11:12

sovanlandy


2 Answers

In your case it will be handy to use openstruct

require 'ostruct'

h = OpenStruct.new(name: "john", age: "23")

h.name #=> "john"
h.age  #=> 23
like image 132
megas Avatar answered Dec 18 '22 00:12

megas


Maybe this is what you are looking for

item = Struct.new(:id, :name)
item.new(1, 'Name')
like image 22
develop-ua Avatar answered Dec 18 '22 01:12

develop-ua