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 code editors can’t find the parameter names for a method. Also, Ruby programmers often don’t use these sophisticated code editors and may prefer lightweight and quick code editors without these features.

So, most programmers would prefer to implement the total_weight method in a slightly different way:

def total_weight(options)
  a = options[:soccer_ball_count]
  b = options[:tennis_ball_count]
  c = options[:golf_ball_count]
  puts a
  puts b
  puts c
  # ...
end

params = { soccer_ball_count: 3, tennis_ball_count: 2, golf_ball_count: 1 }
x = total_weight(params)
total_weight({ soccer_ball_count: 3, tennis_ball_count: 2, golf_ball_count: 1 })

We can agree that this method looks much clearer than the previous one.

total_weight(3, 2, 1)

Advantages of passing method parameters

Syntax with passing method parameters as a hash takes more space on the screen, but it has several advantages.

The first is that parameter order is not critical anymore; parameters are named now. In total_weight(3, 2, 1), we need to respect the order and always remember the correct order: the first parameter is for the number of soccer balls and so on. In the case of parameters as a hash, we can provide parameters regardless of order:

total_weight({ golf_ball_count: 1, tennis_ball_count: 2, soccer_ball_count: 3 })

Programming is more fun now, because we don’t have to remember the parameter order. Also, we can simplify that syntax a little bit more and omit curly braces:

total_weight(golf_ball_count: 1, tennis_ball_count: 2, soccer_ball_count: 3)

With all these improvements in mind, we can write the method that calculates the weight can be rewritten like this:

Get hands-on with 1200+ tech skills courses.