...

/

Passing Parameters to Methods

Passing Parameters to Methods

Learn how to pass multiple parameters to methods in Ruby.

Multiple parameters

Let’s say we need to call a method and pass multiple parameters to this method. For example, a user has selected a specific number of soccer balls, tennis balls, and golf balls. We need to create a method to calculate the total weight. We can do this the following way:

def total_weight(soccer_ball_count, tennis_ball_count, golf_ball_count)
  # ...
end

And the method call itself would look like this:

x = total_weight(3, 2, 1)

We have three soccer balls, two tennis balls, and one golf ball. Will you agree that total_weight(3, 2, 1) doesn’t look very readable from the first sight? We know what 3, 2, and 1 are because we created this method. However, for developers from our team, it can be misleading. They have no idea which parameters go first, and they need to examine the source of the total_weight function to understand that.

It’s not super convenient, and some IDEs (integrated development environment) and code editors automatically suggest the names of method parameters. For example, this functionality is implemented in the RubyMine editor. However, Ruby is a dynamically typed programming language, and sometimes even sophisticated ...