我定义了一个采用(数组)数组的方法,例如

def list(projects)
  puts projects.join(', ')
end

list(['a', 'b'])

但是,作为使用仅包含单个String元素的Array进行调用的快捷方式,我希望同一个函数也可以接受单个纯String,例如
  list('a')

在方法内部处理此问题的Ruby方法是什么?

最佳答案

为什么不这样:

def list(*projects)
  projects.join(', ')
end

然后,您可以根据需要调用任意数量的参数
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"

splat(*)会自动将所有参数转换为Array,这将使您可以毫无问题地传递Array和/或String。它也可以与其他对象一起工作
list(1,2,'three',arr,{"test" => "hash"})
#=> "1, 2, three, a, b, c, d, e, f, g, {\"test\"=>\"hash\"}"

感谢@Stefan和@WandMaker指出Array#join可以处理嵌套数组

关于arrays - 如何定义一个采用数组或字符串的Ruby方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31704164/

10-11 23:02
查看更多