Let's say I want a method which will be called like this:
tiger = create_tiger( :num_stripes => 12, :max_speed => 43.2 )
tiger.num_stripes # will be 12
where some of the options have default values:
tiger = create_tiger( :max_speed => 43.2 )
tiger.num_stripes # will have some default value
what's a nice idiomatic ruby way of implementing that defaulting behaviour in the method implementation?
Adding Default Arguments Default arguments are easy to add, you simply assign them a default value with = ("equals") in the argument list. There's no limit to the number of arguments that you can make default. Let's take a look at the different ways we can call this method: greeting # > Hello, Ruby programmer.
Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.
The hashing functions included in Ruby's digest include: MD5, RIPEMED-160, SHA1, and SHA2. Each hashing function will accept an input variable, and the output can be returned in either a digest, hexidecimal, or “bubble babble” format.
In Ruby, the key() method of a hash returns the key for the first-found entry with the given value. The given value is passed as an argument to this method.
def foo(options = {})
options = { ... defaults ... }.merge(options)
end
If you're using Rails (not just plain Ruby), a slightly shorter method is
def foo(options = {})
options.reverse_merge! { ... defaults ... }
end
This has the added advantage of allowing you to do multiple lines a tad bit more cleanly:
def foo(options = {})
options.reverse_merge!(
:some_default => true,
:other_default => 5
)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With