Dan*_*ton 8 ruby syntax conditional if-statement
对不起,如果这是一个愚蠢的问题,但我是一个C#家伙摸索着红宝石的方式..
在红宝石中,我注意到很多人这样做:
do_something(with params) if 1 = 1
Run Code Online (Sandbox Code Playgroud)
这和之间有什么区别(甚至是轻微的):
if 1 = 1 do_something(with params)
Run Code Online (Sandbox Code Playgroud)
还是为了更清晰而写的是同一件事?
后者在语法上无效.你需要写:
if 1==1 then do_something(with params) end
Run Code Online (Sandbox Code Playgroud)
单线条件必须始终跟踪.而且,是的,是有区别的.试试这些:
bar1 = if foo1=14
foo1*3
end
#=> 42
bar2 = foo2*3 if foo2=14
#=> NameError: undefined local variable or method `foo2' for main:Object
Run Code Online (Sandbox Code Playgroud)
在后者中,Ruby在引用之后看到赋值,因此将其foo2
视为方法而不是局部变量.这只是一个问题:
它是语法糖...允许我们以更易于阅读的方式编写代码。
http://rubylearning.com/satishtalim/ruby_syntropic_sugar.html
注意:对于@Phrogz,以下内容不相同!请确保您没有尝试将值分配给变量,而是尝试将变量与值进行比较!另外,正如 Phrogz 提到的,变量赋值的顺序有很大的不同......有关更多详细信息,请参阅@Phrogz 答案!
if 1 = 1 then do_something(with params) end
if 1 == 1 then do_something(with params) end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6520 次 |
最近记录: |