4

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?

7
  • What's wrong with h[name] or h[age]? Commented Apr 22, 2013 at 6:33
  • In a rabl template, where i just want to render a hash, not an object. Commented Apr 22, 2013 at 6:40
  • If it is a hash, then it is an object. Commented Apr 22, 2013 at 6:45
  • I just check rabl doc they also recommend openstruct. github.com/nesquena/rabl/wiki/Rendering-hash-objects-in-rabl Commented Apr 22, 2013 at 6:46
  • I agree with squiguy, h[:name] or h[:age] is what you have. Why put in all that overhead to make a method out of it? Commented Apr 22, 2013 at 6:49

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

Comments

3

Maybe this is what you are looking for

item = Struct.new(:id, :name)
item.new(1, 'Name')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.