Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a Ruby method that either takes an Array or a String?

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?

like image 285
sschuberth Avatar asked Jul 29 '15 15:07

sschuberth


Video Answer


1 Answers

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

like image 72
engineersmnky Avatar answered Sep 26 '22 01:09

engineersmnky