为了写得更简洁,而不是这样做:
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()
正如讨论的那样,是不允许的在另一个问题中 https://stackoverflow.com/questions/1380331/conditional-statement-and-assigning-value-in-ruby,并且根据 Matz 的说法,在 1.9 中仍将保持这种状态(http://redmine.ruby-lang.org/issues/show/1141 http://redmine.ruby-lang.org/issues/show/1141).
考虑到赋值和比较可能会造成混淆,这是否会使代码变得难以阅读?
在条件语句中使用赋值是一种很好的风格。如果这样做,请将条件括在括号中。
# 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
请参阅社区风格指南以获取更多信息 https://github.com/bbatsov/ruby-style-guide#safe-assignment-in-condition
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)