[ACCEPTED]-Is there a way to initialize an object through a hash?-initialization
Accepted answer
You can define an initialize function on 3 your class:
class A
attr_accessor :b,:c,:d
def initialize(h)
h.each {|k,v| public_send("#{k}=",v)}
end
end
Or you can create a module and 2 then "mix it in"
module HashConstructed
def initialize(h)
h.each {|k,v| public_send("#{k}=",v)}
end
end
class Foo
include HashConstructed
attr_accessor :foo, :bar
end
Alternatively 1 you can try something like constructor
OpenStruct
is worth considering:
require 'ostruct' # stdlib, no download
the_hash = {"b"=>10, "c"=>20, "d"=>30}
there_you_go = OpenStruct.new(the_hash)
p there_you_go.c #=> 20
0
instance_variable_set
is intended for this kind of use case:
class A
def initialize(h)
h.each {|k,v| instance_variable_set("@#{k}",v)}
end
end
It's 7 a public method, so you could also call 6 it after construction:
a = A.new({})
a.instance_variable_set(:@foo,1)
But note the implied 5 warning in the documentation:
Sets the instance variable 4 names by symbol to object, thereby frustrating 3 the efforts of the class’s author to attempt 2 to provide proper encapsulation. The variable 1 did not have to exist prior to this call.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.