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}"
endirb> 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}"
endirb> 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
endirb> 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.
Ruby Mastery
We’re currently finalizing our first online course: Ruby Mastery.
Join the list for an exclusive release alert! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚