条件语句中的赋值是否是良好的红宝石样式? [英] Is assignment in a conditional clause good ruby style?

查看:47
本文介绍了条件语句中的赋值是否是良好的红宝石样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了简洁起见,而不是这样做:

In order to write more concisely, rather than do this:

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

这是不好的风格吗?更简洁的语法:

Is this bad style? The still-more-concise syntax:

do_something_with test_value if test_value = method_call_that_might_return_nil()

不允许

,如在另一个SO问题中讨论的那样,根据Matz( http://redmine.ruby-lang.org/issues/show/1141 ).

is not allowed, as discussed in another SO question, and will remain that way in 1.9, according to Matz (http://redmine.ruby-lang.org/issues/show/1141).

鉴于赋值和比较可能会造成混淆,这是否使阅读代码变得太难了?

Given the possible confusion of assignment and comparison, does this make it too hard to read the code?

推荐答案

在条件条件中使用赋值是一种很好的风格.如果这样做,则将条件括在括号中.

It is GOOD style to use assignments in conditionals. If you do so, wrap the condition in parentheses.

# 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

有关详细信息,请参阅社区样式指南.

这篇关于条件语句中的赋值是否是良好的红宝石样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆