ruby - 条件子句中的赋值是好的 ruby​​ 风格吗?

标签 ruby coding-style

为了写的更简洁,不如这样:

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

See the community style guide for more information

关于ruby - 条件子句中的赋值是好的 ruby​​ 风格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966585/

相关文章:

email - HTML 电子邮件是什么样的?

ruby - 为什么 open ('uri' ).read 会删除响应数据?

ruby - 将参数传递给 ruby​​ 方法有哪些不同的可能性?参数/哈希表/数组/aproc?

java - 抛出异常的 Java 方法是否有特定的命名约定?

c# - 访问继承属性时是否应该使用 "base."前缀

testing - AutoIt 最佳实践/编码风格

scala - 如何在Scala中用更少的括号写f(g(h(x)))?

mysql - 优化通过 has_many :through association 检索 ID 的方式

ruby - 如何将模块命名空间添加到 ruby​​ 类/模块?

ruby - 简化字符串乘法连接