← Back to Ruby Course | Chapter 7: Methods | Lesson 2 of 7

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:

  1. Parameters
Syntax
ruby
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

markup
def greet(name, times)
  times.times { puts "Hello, #{name}!" }
end

greet("Sam", 2)
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
  1. Passing the wrong number of arguments, which raises ArgumentError (wrong number of arguments).
  2. Passing arguments in the wrong order, such as greet(2, "Sam").
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.