Ruby Keyword Argument Tutorial

In this section, we will learn what the keyword argument is and how to use it in Ruby.

What is Keyword Argument in Ruby?

The Ruby keyword argument is a way of creating Ruby methods with parameters that allow us to use the name of those parameters when calling the target method in order to pass arguments to it.

So far, when we create a method with parameters, we pass arguments to the method in order! So the first argument is passed to the first parameter, the second argument to the second parameter and so on.

But using the keyword argument, we can explicitly define what value should be passed to what parameter of the target method! Also in that case, the order of arguments does not matter anymore! Because now we are explicitly defining the argument for each parameter of the method using the parameter name.

How to Create Keyword Argument Method in Ruby?

Here’s the syntax of how to create a keyword argument method:

def function_name (parameter1: optional_value, parameter2, optional_value2, parameter_n: optional_value_n)

#instructions...

end

The parameters of the method now have the colon symbol and there’s one optional value for each parameter as well.

Note that there’s no need to set an optional value for a parameter!

For example:

def function_name (first_name: , last_name: “Doe”, age: 100)…

Here both `last_name` and `age` parameter have default value but then the `first_name` doesn’t have one.

Now whenever we call the target method, we need to use the name of parameters and pass the value to them.

For example:

function_name (first_name: “John”, last_name: “Doe”, age:200)

Note: when calling a keyword argument method, you don’t need to set a value for those parameters that already have an optional value assigned to them! In that case the default value will be used instead.

But if there’s a parameter that does not have the default argument, you should call the parameter at the time of calling the method and set a value for that parameter. Otherwise you’ll get an error.

Example: creating keyword argument method in Ruby

def print_name (first_name:, last_name:"Bauer", age:100)

    puts first_name, last_name, age

end

print_name(first_name: "John", last_name:"Doe")

Output:

John

Doe

100
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies