Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters with default values before positional parameters [duplicate]

Tags:

ruby

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.

like image 723
daremkd Avatar asked Sep 13 '26 17:09

daremkd


1 Answers

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
end

This 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

like image 86
Alex Avatar answered Sep 15 '26 12:09

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!