Default parameters
suggest changedef make_animal_sound(sound = 'Cuack')
puts sound
end
Examples
make_animal_sound('Mooo') # Mooo
make_animal_sound # Cuack
It’s possible to include defaults for multiple arguments:
def make_animal_sound(sound = 'Cuack', volume = 11)
play_sound(sound, volume)
end
make_animal_sound('Mooo') # Spinal Tap cow
However, it’s not possible to supply the second without also supplying the first. Instead of using positional parameters, try keyword parameters:
def make_animal_sound(sound: 'Cuack', volume: 11)
play_sound(sound, volume)
end
make_animal_sound(volume: 1) # Duck whisper
Or a hash parameter that stores options:
def make_animal_sound(options = {})
options[:sound] ||= 'Cuack'
options[:volume] ||= 11
play_sound(options[:sound], options[:volume])
end
make_animal_sound(:sound => 'Mooo')
A default can be any Ruby expression. It runs in the method each time that argument is omitted, so it can even declare local variables. This will not get through code review. Courtesy of caius for pointing this out.
def make_animal_sound( sound = ( raise 'TUU-too-TUU-too...' ) ); p sound; end
make_animal_sound 'blaaaa' # => 'blaaaa'
make_animal_sound # => TUU-too-TUU-too... (RuntimeError)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents