ssc*_*rth 9 ruby arrays string
我定义了一个采用数组(字符串)的方法,比如
def list(projects)
puts projects.join(', ')
end
list(['a', 'b'])
Run Code Online (Sandbox Code Playgroud)
但是,作为使用仅由单个String元素组成的Array调用它的简写,我希望同样的函数也接受单个普通的String
list('a')
Run Code Online (Sandbox Code Playgroud)
在方法中处理这个问题的Ruby方法是什么?
为什么不是这样的:
def list(*projects)
projects.join(', ')
end
Run Code Online (Sandbox Code Playgroud)
然后你可以随意调用它
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"
Run Code Online (Sandbox Code Playgroud)
splat(*)会自动将所有参数转换为数组,这将允许您毫无问题地传递数组和/或字符串.它也适用于其他对象
list(1,2,'three',arr,{"test" => "hash"})
#=> "1, 2, three, a, b, c, d, e, f, g, {\"test\"=>\"hash\"}"
Run Code Online (Sandbox Code Playgroud)
谢谢@Stefan和@WandMaker指出Array#join可以处理嵌套的数组
| 归档时间: |
|
| 查看次数: |
3337 次 |
| 最近记录: |