I am able to define a method like this:
def test(id, *ary, hash_params)
# Do stuff here
end
But this makes the hash_params
argument mandatory. These don't work either:
def t(id, *ary, hash_params=nil) # SyntaxError: unexpected '=', expecting ')'
def t(id, *ary, hash_params={}) # SyntaxError: unexpected '=', expecting ')'
Is there a way to make it optional?
The splat operator is useful not only for destructuring arrays but also for constructing them.
In both Ruby and JavaScript, you can use splat/spread to build up a new array from existing arrays.
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.
Splat operator or start (*) arguments in Ruby define they way they are received to a variable. Single splat operator can be used to receive arguments as an array to a variable or destructure an array into arguments. Double splat operator can be used to destructure a hash.
There is support for this in ActiveSupport through the use of the array extension extract_options!
.
def test(*args)
opts = args.extract_options!
end
If the last element is a hash, then it will pop it from the array and return it, otherwise it will return an empty hash, which is technically the same as what you want (*args, opts={})
to do.
ActiveSupport Array#extract_options!
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