In message "[ruby-talk:5600] passing single or multiple strings."
on 00/10/17, Hugh Sasse Staff Elec Eng <hgs / dmu.ac.uk> writes:
> def something(args)
> *bunch_of_args = args
> bunch_of_args.each do
> ...
> end
> end
>
>That's fine, and quite useful; if args are Strings and I just get one
>string then I don't get caught out by wanting to write:
>
> case args.type
> when Array
> ...
> when String
> ...
> end
>
>which does not work. (You have to use if args.type == Array...elsif....
>for that.)
`type' is not needed because `Klass === obj' is identical to
`obj.is_a? Klass.'
def something(args)
case args
when Array
:Array
when String
:String
end
end
p something([]) #=> :Array
p something("") #=> :String
>But this is quite different:
>
> def something(*bunch_of_args)
> bunch_of_args.each do
> ...
> end
> end
>
>because then things are not "shelled" out and if I pass in an Array I get
>a nested Array. something(["x", "y"]) => bunch_of_args == [["x", "y"]]
>
>So what method of Array, if any, will do this "shelling" for me?
How about something(*["x", "y"]);
def something(*bunch_of_args)
bunch_of_args
end
p something(*["x", "y"]) #=> ["x", "y"]
-- gotoken