Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 484
Geo Avatar asked Oct 15 '09 14:10

Geo


People also ask

How do you initialize a hash?

Another initialization method is to pass Hash. new a block, which is invoked each time a value is requested for a key that has no value. This allows you to use a distinct value for each key. The block is passed two arguments: the hash being asked for a value, and the key used.

What is used to initialize an object?

Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

How do you add to a hash?

Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.

What is initialize method in Ruby?

The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object. Below are some points about Initialize : We can define default argument. It will always return a new object so return keyword is not used inside initialize method.


1 Answers

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

like image 173
jrhicks Avatar answered Oct 07 '22 21:10

jrhicks