How to define a Ruby method that either takes an Array or a String?
You can check the type of the input, for example:
>> a = ['foo', 'bar']
=> ['foo', 'bar']
>> a.is_a? Array
=> true
you can also check string with is_a?
You would end up with something link:
def list(projects)
if projects.is_a? Array
puts projects.join(', ')
else
puts projects
end
end
list('a') # a
list(['a', 'b']) # a, b
You have many ways of doing this in Ruby, respond_to?
and kind_of?
also work
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