views:

78

answers:

1

If I have this class:

class A
  attr_accessor :b,:c,:d
end

and this code:

a = A.new
h = {"b"=>10,"c"=>20,"d"=>30}

is it possible to initialize the object directly from the hash, without me needing to go over each pair and call instance_variable_set? Something like:

a = A.new(h)

which should cause each instance variable to be initialized to the one that has the same name in the hash.

+6  A: 

You can define an initialize function on your class:

class A
  attr_accessor :b,:c,:d
  def initialize(h)
    h.each {|k,v| send("#{k}=",v)}
  end
end

Or you can create a module and then "mix it in"

module HashConstructed
 def initialize(h)
  h.each {|k,v| send("#{k}=",v)}
 end
end

class Foo
 include HashConstructed
 attr_accessor :foo, :bar
end

Alternatively you can try something like constructor

jrhicks