Turn hash into object variables?


(Ruby Baby) #1

I know beautiful Ruby has an easier way to do this:

class SomeClass
def initialize(someHash)
@name = someHash[‘name’]
@address = someHash[‘address’]
@blah = someHash[‘blah’]
# etc for many key=>value pairs …
end
end

How can I make it do that for every key in the hash?


(Gavin Sinclair) #2

I know beautiful Ruby has an easier way to do this:

class SomeClass
def initialize(someHash)
@name = someHash[‘name’]
@address = someHash[‘address’]
@blah = someHash[‘blah’]
# etc for many key=>value pairs …
end
end

Hash#values_at(k1, k2, …)

How can I make it do that for every key in the hash?

Using OpenStruct gets you halfway there.

require 'ostruct’
h = { :name => “John”, :age => 42 }
o = OpenStruct.new(h)
o.name # -> "John"
o.age # -> 42

If you want to apply it to arbitrary classes, I suggest you write a module
that implements the “from_hash” method.

class SomeClass
extend FromHash
def initialize
end
end

sc = SomeClass.from_hash(h) # ‘h’ as above
sc.name # -> “John”

Cheers,
Gavin