Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a method in ruby using splat and an optional hash at the same time? [duplicate]

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?

like image 587
andersonvom Avatar asked Dec 19 '12 20:12

andersonvom


People also ask

What are two uses of the splat operator?

The splat operator is useful not only for destructuring arrays but also for constructing them.

Is there a spread operator in Ruby?

In both Ruby and JavaScript, you can use splat/spread to build up a new array from existing arrays.

What hash function does Ruby use?

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.

What does splat do Ruby?

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.


1 Answers

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!

like image 105
Cluster Avatar answered Sep 22 '22 05:09

Cluster