I’d like to allow the user to pass an option to a method that can be either a single object or an array. The below code works, assuming `opts[:variable_length_opt] is defined:
def initialize(opts={})
@ivar = *opts[:variable_length_opt]
end
But I’d also like to be able to set a default if the option is not set. But this code does not work:
def initialize(opts={})
@ivar = (opts[:variable_length_opt] ? *opts[:variable_length_opt] : default_value)
end
It throws an unexpected tSTAR error. I understand there are other, more verbose methods to accomplish what I’m after, but I am wondering if there are other, as-short alternatives. Also, what are the limits of the splat? I can’t think of a good reason that it should be unavailable here.
I think splats are only available in assignments (and indirectly, in method calls). You can’t call splat directly either:
In your case, you can do something like:
That is almost as short.
But you usually use the splat to assign multiple variables from an array, like
Why do you need the splat in this case?