I defined a method that takes an Array (of Strings), like
def list(projects)
puts projects.join(', ')
end
list(['a', 'b'])
However, as a short-hand for calling it with an Array that only consists of a single String element, I'd like the same function to also accept a single plain String like
list('a')
What would be the Ruby way to handle this inside the method?
Why not something like this:
def list(*projects)
projects.join(', ')
end
Then you can call it with as many arguments as you please
list('a')
#=> "a"
list('a','b')
#=> "a, b"
arr = %w(a b c d e f g)
list(*arr)
#=> "a, b, c, d, e, f, g"
list(arr,'h','i')
#=> "a, b, c, d, e, f, g, h, i"
The splat (*) will automatically convert all arguments into an Array, this will allow you to pass an Array and/or a String without issue. It will work fine with other objects too
list(1,2,'three',arr,{"test" => "hash"})
#=> "1, 2, three, a, b, c, d, e, f, g, {\"test\"=>\"hash\"}"
Thank you @Stefan and @WandMaker for pointing out Array#join
can handle nested Arrays
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