Keyword arguments

Ruby

Since Ruby 2.0 we are able to use keywords arguments in our methods. What does it mean? Let’s consider following example:

def show_video(video, width, height)
  player = Player.new(video)
  player.width = width
  player.height = height
  player.render
end

show_video(video, 300, 200)

This is an example of positional arguments and as you know you can’t change an order of those arguments otherwise you will assign the wrong value to wrong argument. With keyword arguments our method looks following:

def show_video(video:, width:, height:)
  player = Player.new(video)
  player.width = width
  player.height = height
  player.render
end

show_video(video: video, width: 300, height: 200)

Benefits?

Without looking at the method body you are able to say what given variable may be used for. With positional arguments, it would be hard because you see only values and have no idea what are they used for if you didn’t see method body before.

Since Ruby 2.1 there are also required keyword arguments available. So if you want to require only video argument we have to modify our method:

def show_video(video:, width: 300, height: 200)
  player = Player.new(video)
  player.width = width
  player.height = height
  player.render
end

show_video(video: video)

Basically, to make a keyword argument not required we have to set it default value otherwise it would be required and error would be raised if you will not pass given argument. Personally, I fall in love with that kind of arguments as they are super readable and with the proper naming, you can tell what given method is doing only by looking at the method name and arguments.

If you are still using Ruby 1.x it’s a great reason to upgrade!