不能在Ruby中使用三元运算符的假部分中的break [英] Can't use break in the false part of the ternary operator in Ruby
本文介绍了不能在Ruby中使用三元运算符的假部分中的break的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下面的代码作为示例:
此代码有效
i = 0
flag = false
while i < 10
flag = true
if flag
i+=1
else
break
end
end
但是当将If部分转换为三元运算符时
But when turn If part into ternary operator like this
i = 0
flag = false
while i < 10
flag = true
if flag ? i+=1 : break
end
我收到此错误:
ternary.rb:5: void value expression
ternary.rb:6: syntax error, unexpected end-of-input, expecting keyword_end
我知道这段代码缺乏逻辑,但是当前示例是我想出的最好的例子
I know this code lacks of logic, but the current example is the best what I came up with to show you what I've encountered with.
推荐答案
您的代码中有语法问题。您不能在三元运算符?:
中使用 if
,这在代码行如果标志? i + = 1:break
There is syntax issue in your code. You can't use if
in ternary operator ?:
as can be seen in your code line if flag ? i+=1 : break
这里是编写代码的一种方式:
我可以自由地修改代码,以便它说明可以使用中断
。
Here is one way of writing the code:
I have taken liberty to modify the code so that it illustrates that break
can be used.
i = 0
flag = true
while i < 10
flag = false if i > 5
flag ? i+=1 : break
end
p i
#=> 6
这篇关于不能在Ruby中使用三元运算符的假部分中的break的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文