๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Method Arguments

Arguments are values given to a method in a call. A method declares parameters to receive the values and work with them.

One parameter

The greet method declares one parameter named name. Each call passes one argument, and the greeting uses the value it received.

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

greet("Ana")
greet("Ben")

Two arguments

The introduce method declares two parameters. Each call passes two arguments, and the first fills name while the second fills city.

def introduce(name, city)
  puts "#{name} lives in #{city}."
end

introduce("Ana", "Oslo")
introduce("Ben", "Perth")

A default value

The name parameter carries a default value of friend. A call with no argument uses the default, and a call with an argument uses that argument.

def greet(name = "friend")
  puts "Hello, #{name}!"
end

greet
greet("Ana")

Implicit return and the return word

The double_plain method names no return word, so its last expression is the return value. The double_word method writes return before the same expression, and both calls print 42.

def double_plain(number)
  number * 2
end

def double_word(number)
  return number * 2
end

puts double_plain(21)
puts double_word(21)

Too few arguments

The introduce method needs two arguments. This call passes only one, so the program stops with an ArgumentError.

def introduce(name, city)
  puts "#{name} lives in #{city}."
end

introduce("Ana")

Example

def total(count, each = 5)
  count * each
end

puts total(3)
puts total(3, 8)
puts total(4, 8)

Key points

  • A parameter is a name declared in a method definition.
  • An argument is a value passed in a call.
  • Arguments fill the parameters in order.
  • A default value fills a parameter when a call leaves the argument out.
  • The last expression in a method is its return value.
  • Writing return before an expression makes that expression the return value.
  • A call with too few arguments raises an ArgumentError.

In this example, the total method multiplies a count by a price named each. The first call leaves out the second argument, so the default price of 5 applies and the call returns 15. The second call passes 8 as the price and returns 24. The third call passes a count of 4 and a price of 8, and it returns 32.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

What is the return value of a method whose last line is number * 2 when the method is called with 6?