为了写的更简洁,不如这样:
test_value = method_call_that_might_return_nil()
if test_value
do_something_with test_value
end
我一直在条件分配:
if test_value = method_call_that_might_return_nil()
do_something_with test_value
end
这是糟糕的风格吗?更简洁的语法:
do_something_with test_value if test_value = method_call_that_might_return_nil()
是不允许的,正如所讨论的in another SO question ,根据 Matz ( http://redmine.ruby-lang.org/issues/show/1141 ) 的说法,在 1.9 中将保持这种状态。
考虑到赋值和比较可能会混淆,这是否会使代码难以阅读?
最佳答案
在条件语句中使用赋值是一种很好的风格。如果这样做,请将条件括在括号中。
# bad (+ a warning)
if v = array.grep(/foo/)
do_something(v)
# some code
end
# good (MRI would still complain, but RuboCop won't)
if (v = array.grep(/foo/))
do_something(v)
# some code
end
# good
v = array.grep(/foo/)
if v
do_something(v)
# some code
end
关于ruby - 条件子句中的赋值是好的 ruby 风格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966585/