Method Arguments
Simple method declarations include a comma-separated list of argument names (in optional parentheses) after the method name. But there is much more to Ruby’s method arguments. The subsections that follow explain:
How to declare an argument that has a default value, so that the argument can be omitted when the method is invoked
How to declare a method that accepts any number of arguments
How to simulate named method arguments with special syntax for passing a hash to a method
How to declare a method so that the block associated with an invocation of the method is treated as a method argument
Parameter Defaults
When you define a method, you can specify default values for some or all of the parameters. If you do this, then your method may be invoked with fewer argument values than the declared number of parameters. If arguments are omitted, then the default value of the parameter is used in its place. Specify a default value by following the parameter name with an equals sign and a value:
def prefix(s, len=1) s[0,len] end
This method declares two parameters, but the second one has a default. This means that we can invoke it with either one argument or two:
prefix("Ruby", 3) # => "Rub"
prefix("Ruby") # => "R"
Argument defaults need not be constants: they may be arbitrary expressions, and can refer to instance variables and to previous parameters in the parameter list. For example:
# Return the last character of s or the substring from index to the end def suffix(s, index=s.size-1) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access