My Ruby 💌 newsletter 💌 is available here ! Feel free to subscribe ! 🚀

Method Arguments in Ruby: Part II

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}"
end
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}"
end
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
blk.call
end
irb> method_with_block { puts 'a block' }
Proc
a block
=> nil

Here we can see that blk is an instance of Proc and that calling blk.call 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à !


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.