I would like to initialize class with a the individual members of the hash set to default values, I have tried the following:
class SomeClass
attr_accessor :hello, :holla
def initialize ( hash = { hello: 'world', holla: 'mundo'})
@hello = hash[:hello]
@else = hash[:holla]
end
end
which works as desired if do not input any argument
p = SomClass.new
puts "should be 'world'"
puts p.hello
puts "should be 'mundo'"
puts p.holla
$ruby hello_world.rb
should be 'world'
universe
should be 'mundo'
mundo
but if one of the augments of the hash is set the other is left empty, for example:
p = SomeClass.new( { hello: 'universe'})
puts "should be 'universe'"
puts p.hello
puts "should be 'mundo'"
puts p.holla
$ruby hello_world.rb
should be 'universe'
universe
should be 'mundo'
How do I input hash as the argument for an initialization in manor that sets the default values for the individual members of the hash just the hash it self?
There is no way to do this without custom code. The simplest version of that would be:
That will allow additional properties to be passed in the hash, but I assume that is desirable since you deliberately used an extensible input to start with.