我有一个布尔值来检查它是否为真,然后设置一个局部变量.我如何重构这一点,以便更多Ruby-ish?
if firm.inflection_point
inflection_point = 1
else
inflection_point = 0
end
Run Code Online (Sandbox Code Playgroud)
rud*_*ph9 61
inflection_point = (firm.inflection_point ? 1 : 0)
Run Code Online (Sandbox Code Playgroud)
saw*_*awa 17
如果你只是在某一点上,那么rudolph9的答案是好的,但是如果你在整个地方都有类似的逻辑,那么对于猴子补丁的一般用途可能是有意义的:
class FalseClass; def to_i; 0 end end
class TrueClass; def to_i; 1 end end
inflection_point = firm.inflection_point.to_i
Run Code Online (Sandbox Code Playgroud)
在Ruby中,你应该保持所有的逻辑处理真值而不是0和1,但我想你正在处理来自某些处理0和处理的外部系统的输入或输出1.然后,这样做会有意义.
And*_*edo 11
另一种选择是使用短路运算符:
inflection_point && 1 || 0
irb(main):001:0> true && 1 || 0
=> 1
irb(main):002:0> false && 1 || 0
=> 0
Run Code Online (Sandbox Code Playgroud)
In Ruby, if is an expression. There's no need to assign to a variable inside the then and else branches, just return the value you want and assign the variable to the result of the if expression:
inflection_point = if firm.inflection_point
1
else
0
end
Run Code Online (Sandbox Code Playgroud)
In simple cases like this, it's more readable to write the entire expression on a single line:
inflection_point = if firm.inflection_point then 1 else 0 end
Run Code Online (Sandbox Code Playgroud)
You can also use the conditional operator, which I personally find to be much less readable:
inflection_point = firm.inflection_point ? 1 : 0
Run Code Online (Sandbox Code Playgroud)
您需要的是一个被称为三元运算符的条件运算,它几乎在所有语言中都使用,并且使用符号 ? 和 :
inflection_point = firm.inflection_point ? 1 : 0
Run Code Online (Sandbox Code Playgroud)
基本上意味着,如果第一个条件计算为真(firm.inflection_point),则返回“?”之后的值 (1) 否则,返回“:”后的值(0)
| 归档时间: |
|
| 查看次数: |
26869 次 |
| 最近记录: |