if some_condition # 这里加 then 是不好的
do_something_if_some_condition
elsif another_condition
do_something_if_another_condition
else
do_something_else
end
# unless...else...end 是不好的
do_something if some_condition
some_condition and do_something # 这句话句意和上面一句相同,暂时可以不用理解。
# if some_condition then do_something end 是不好的
# unless !some_condition 是不好的
do_something_else unless some_condition # do_something if !some_condition 是不好的
some_condition or do_something_else # 这句话句意和上面一句相同,暂时可以不用理解。
# unless condition1 && condition2 是不好的
some_condition ? do_something : do_something_else
# if some_condition then do_something else do_something_else end 是不好的
case expression
when condition1 then do1
when condition2 # 这里加 then 是不好的
do2_line1
do2_line2
# when condition3: do3 #这样写是不好的,并且在Ruby后期版本已经不支持。请务必不要用这样的写法。
else do_else # do_else 内容较长时建议换行
end
# 判断条件成立是用 condition === expression
说的是不能动态的改变
看两个例子
=======================================================[pre lang="ruby" line="1"]CON = 100
p CON
#=>100
CON += 50
#warning: already initialized constant CON
p CON
#=>150
another_var = CON
p another_var #=> 150[/pre]在给常量第一次赋值以后 再对其赋值就会出现警告 但是不出错 继续执行 所以赋值还是能够成功
现在加上这样一段[pre lang="ruby" line="1"]def met
CON += 3
p CON
end #SyntaxError:dynamic constant assignment
met[/pre]这样的话这段代码无法通过语法检查 一句都不会执行 包括上面的100 150等
=======================================================
=======================================================[pre lang="ruby" line="1"]loc = 100
p loc
#=>100
loc += 50
p loc
#=>150
another_var = loc
p another_var #=> 150
def met
loc += 3
p loc
end
met
#undefined method '+' for nil:NilClass[/pre]这里也会出错 但是语法是正确的 它会输出100 150 150 然后报错 这里出错的原因是loc是局部变量 无法被met方法获取 但是其他变量可以
而且这里也没有出现警报
我们换成实例变量试试
[pre lang="ruby" line="1"]@ins = 100 # 坑人神句 下面不加井号之间的就是这样的结果
@ins#-=-=-=-=-=-=-=-=-=-=-=-=# = 100 #←把井号及之间的删掉
p @ins
#=>100
@ins#-=-=-=-=-=-=-=-=-=-=-=-=# += 50 #←把井号及之间的删掉
p @ins
#=>150
another_var = @ins
p another_var #=> 150