rudolph9
rudolph9

Reputation: 8119

Inputting a hash with default values

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?

Upvotes: 2

Views: 942

Answers (1)

Daniel Pittman
Daniel Pittman

Reputation: 17192

There is no way to do this without custom code. The simplest version of that would be:

def initialize(hash = {})
  hash = {hello: "world", holla: "mondo"}.merge(hash)
  # now your default values are set, but will be overridden by the passed argument
end

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.

Upvotes: 5

Related Questions