Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

ruby - Is there a way to initialize an object through a hash?

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.

question from:https://stackoverflow.com/questions/1572660/is-there-a-way-to-initialize-an-object-through-a-hash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can define an initialize function on 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 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 you can try something like constructor


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...