ali
ali

Reputation: 404

using hashes like objects in rails

i think i saw once a nice solution in a rails project. this solution was built in rails i think.

what i want to get is an hashlike object, that does something like this:

jar = Jar.new #no defined methods 'name' in it!

jar.name #returns nil
jar.name = 'fu'
jar.name #return 'fu'

where name can be everything possible much like a hash works. i dont want to predefine it!

is there a helper class that does this in rails or something similar?

Upvotes: 0

Views: 1075

Answers (2)

Erez Rabih
Erez Rabih

Reputation: 15808

You can use OpenStruct which is in Ruby core:

require 'ostruct'

person = OpenStruct.new
person.name    = "John Smith"
person.age     = 70
person.pension = 300

puts person.name     # -> "John Smith"
puts person.age      # -> 70
puts person.address  # -> nil

Also, have a look at the documentation.

Upvotes: 4

apneadiving
apneadiving

Reputation: 115541

You can use an openstruct:

require 'ostruct'
=> true 
o = OpenStruct.new
=> #<OpenStruct>
o.foo
=> nil 
o.foo= 1
=> 1 
o.foo
=> 1 

Upvotes: 1

Related Questions