Parameters
Parameters are the blanks a method asks you to fill in when you call it, like the size and flavor for an ice cream order. Your choices shape what the method does.
In this page:
Syntax
def method_name(param1, param2)
# body
end
method_name(arg1, arg2)
Parameters
Method parameters are listed in the definition's parentheses and become local variables available inside the method body. Arguments are matched positionally by default, in the order they're passed at the call site.
Ruby raises an ArgumentError if the number of arguments doesn't match what the method expects (unless defaults or splat parameters are used).
Note:
Ruby raises ArgumentError immediately if you call a method with the wrong number of required arguments.
Example: Parameters
def greet(name, times)
times.times { puts "Hello, #{name}!" }
end
greet("Sam", 2)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Passing the wrong number of arguments, which raises
ArgumentError (wrong number of arguments). - Passing arguments in the wrong order, such as
greet(2, "Sam"). - Expecting the method to change the caller's variable by reassigning a parameter, when reassigning a parameter changes only the local copy.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: