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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With