Method Arguments in Ruby: Part II

Mehdi Farsi
May 15, 2018 · 2 min read

In this article we’re going to explore the following topics:

  • keyword arguments
  • block as argument

NB: feel free to have a look to Method Arguments in Ruby: Part I before to read this article.

keyword arguments

Keyword arguments are an alternative to positional arguments. They’re pretty similar to passing a hash to a method, but with more explicit errors.

Here, is an example of how to implement and use keyword arguments

def method_with_keyword_arguments(foo: 'bar')
"foo is #{foo}"
irb> method_with_keyword_arguments foo: 'naughty'
=> "foo is naughty"
irb> method_with_keyword_arguments
=> "foo is bar"

Here, the method expects a foo keyword. Otherwise, it’ll use the default value 'bar'. Here, the foo keyword is optional.

So, let’s make it required

def method_with_required_ka(foo:)
"foo is #{foo}"
irb> method_with_required_ka foo: 'naughty'
=> "foo is naughty"
irb> method_with_required_ka
ArgumentError (missing keyword: foo)

A keyword argument becomes required when it’s declared without a default value.

In this case, if the argument is not passed at method call then an explicit ArgumentError with the name of the missing keyword is raised.

block as argument

The ampersand parameter & allows you to automatically store the content of a block in an instance of Proc which is assigned to the ampersand parameter

def method_with_block &blk
p blk.class
irb> method_with_block { puts 'a block' }
a block
=> nil

Here we can see that blk is an instance of Proc and that calling will act as same as calling yield but with the Proc object specificities.

NB: feel free to have a look to Procs and Lambdas article if you’re unfamiliar with Proc objects.

Voilà !

May I have your attention please 🎤🎤

Feel free to subscribe here:

Thank you for taking the time to read this post :-)

Feel free to 👏 and share this Medium post if it has been useful for you.

Here is a link to my last medium post: Method Arguments in Ruby: Part I.


E-Learning platform for Ruby and Ruby on Rails

Mehdi Farsi

Written by

Founder of — I blog about Ruby & ROR - Paris


E-Learning platform for Ruby and Ruby on Rails

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade