我想允许用户将选项传递给可以是单个对象或数组的方法.假设`opts [:variable_length_opt]被定义,下面的代码可以工作:
def initialize(opts={})
@ivar = *opts[:variable_length_opt]
end
Run Code Online (Sandbox Code Playgroud)
但是如果没有设置选项,我也希望能够设置默认值.但是这段代码不起作用:
def initialize(opts={})
@ivar = (opts[:variable_length_opt] ? *opts[:variable_length_opt] : default_value)
end
Run Code Online (Sandbox Code Playgroud)
它抛出一个unexpected tSTAR错误.我知道还有其他更冗长的方法来完成我所追求的目标,但我想知道是否有其他的,简短的替代方案.另外,splat的限制是什么?我想不出有一个很好的理由,它应该在这里不可用.
我认为splats只能在赋值中使用(间接地,在方法调用中).你不能直接调用splat:
1.9.3p286 :045 > *[1,2,3,4]
SyntaxError: (irb):45: syntax error, unexpected '\n', expecting tCOLON2 or '[' or '.'
from /Users/fcoury/.rvm/rubies/ruby-1.9.3-p286/bin/irb:16:in `<main>'
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以执行以下操作:
def initialize(opts={})
@ivar = *(opts[:variable_length_opt] ? opts[:variable_length_opt] : [default_value])
end
Run Code Online (Sandbox Code Playgroud)
这几乎是短暂的.
但是你通常使用splat从数组中分配多个变量,比如
a = [1,2,3,4]
b, c, d, e = *a
b #=> 1
c #=> 2 ...
Run Code Online (Sandbox Code Playgroud)
在这种情况下,为什么需要splat?
| 归档时间: |
|
| 查看次数: |
573 次 |
| 最近记录: |