I have this code:
Will this Ruby code work:
def greeting(name='Derek', country)
print("Hello #{name} from #{country}")
end
greeting("USA")
This code it works (it prints "Hello Derek from USA".
If you ran similar code in Python, it would produce an error because Python doesn't allow parameters with default values before required parameters.
But Ruby does. How? I haven't seen any reference in the documentation to positional vs. parameters with default values.
Because you only gave one argument, the required argument was assigned first, if you provide two arguments then they are assigned in order:
def greeting(name='Derek', country)
puts "Hello #{name} from #{country}"
end
greeting("SO", "USA")
#=> Hello SO from USA
etc, for any number of arguments:
def greeting(name='Derek', city, country)
puts "Hello #{name} from #{city}, #{country}"
end
greeting("City", "USA")
#=> Hello Derek from City, USA
greeting("SO", "City", "USA")
#=> Hello SO from City, USA
The default value does not need to appear first, but arguments with defaults must be grouped together. This is ok:
def add_values(a = 1, b = 2, c) a + b + c endThis will raise a
SyntaxError:def add_values(a = 1, b, c = 1) a + b + c end
https://docs.ruby-lang.org/en/3.3/syntax/methods_rdoc.html#label-Default+Values
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