似乎应该有更好的方法来做到这一点:
def some_method(argument = 'foo')
bar = argument == 'foo' ? 'foo' : "#{argument.to_s}_foo"
# ... do things with bar ...
end
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?我也玩过
bar = ("#{argument}_" if argument != 'foo').to_s + argument
Run Code Online (Sandbox Code Playgroud)
但如果有什么看起来更复杂
从你的榜样,你似乎并不需要为不同的变量foo,并argument在所有的(如果你以后都需要他们,这将是不同的,但是从你的例子似乎并不像它).
简化将是:
def some_method(bar = 'foo')
unless bar == 'foo'
bar = "#{bar}_foo"
end
# Do things with bar
end
Run Code Online (Sandbox Code Playgroud)
当然,unless如果您愿意,可以进行内联:
bar = "#{bar}_foo" unless bar == 'foo'
Run Code Online (Sandbox Code Playgroud)
附注:to_s插值时无需调用.Ruby会为你做到这一点.
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |