Keywords arguments in Ruby

Giovanni Benussi
2 min readMay 11, 2017

Since Ruby 2.0 we can use keywords arguments, which helps us to write code that is easier to read and more explicit.

Let’s suppose that we have a method to send an sms message:

def send_sms(from, to, message)
# send message...
end

We can use this method this way

send_sms(‘+00987654321’, ‘+12345678900’, ‘Hello!’)

Is very clear right?

But also, it can be used this way:

# Sherlock is sending an sms to John or vice versa?
send_sms(sherlock, john, 'Hello!')

Sure, the reader (maybe ourselves in the future) can go to the method definition and that is, but we are software writers. We have to make it better.

If we can avoid the go-to-definition culture, and instead, write good code novels, we will reduce the overall time spent reading code for all.

The solution is very simple, in Ruby you have Keyword Arguments:

def send_sms(from: nil, to: nil, message: 'Hello!')
# send message...
end

This way, we specify the parameters in any order when we call our method:

# These are the same:
send_sms(from: sherlock, to: john, message: 'Hey John, I need your help!')
send_sms(message: 'Hey John, I need your help!', to: john, from: sherlock)

Also, we can force a parameter to be passed:

def send_sms(from:, to:, message: 'Hello!')
# send message...
end

Last, we can mix regular parameters with Keyword Arguments:

def print(message, use_colors: false)
# send message...
end

And we can call it like this:

print('Success')
print('Success', use_colors: true)
print('Success', use_colors: false)

Sure, Keyword Arguments will make your code longer, but it’s worth it.

--

--

Giovanni Benussi
Giovanni Benussi

Written by Giovanni Benussi

Frontend Developer 👨‍💻 Follow me on Twitter 🐦 https://twitter.com/giovannibenussi

No responses yet