“如果"和“如果"有什么区别?带有“then"的语句在最后? [英] What is the difference between "if" statements with "then" at the end?

查看:45
本文介绍了“如果"和“如果"有什么区别?带有“then"的语句在最后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在 if 语句的末尾放置一个 then 时,这两个 Ruby if 语句之间有什么区别?

What's the difference between these two Ruby if statements when we put a then at the end of the if statement?

if(val == "hi") then
  something.meth("hello")
else
  something.meth("right")
end

if(val == "hi")
  something.meth("hello")
else
  something.meth("right")
end

推荐答案

then 是一个分隔符,帮助 Ruby 识别条件和表达式的真实部分.

then is a delimiter to help Ruby identify the condition and the true-part of the expression.

if 条件 then true-part else false-part end

if condition then true-part else false-part end

then 是可选的除非您想在一行中编写一个 if 表达式.对于跨越多行的 if-else-end,换行符作为分隔符将条件与真实部分分开

then is optional unless you want to write an if expression in one line. For an if-else-end spanning multiple lines the newline acts as a delimiter to split the conditional from the true-part

# can't use newline as delimiter, need keywords
puts if (val == 1) then '1' else 'Not 1' end

# can use newline as delimiter
puts if (val == 1)
  '1'
else
  'Not 1'
end

这篇关于“如果"和“如果"有什么区别?带有“then"的语句在最后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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