Can't use break in the false part of the ternary operator in Ruby

不羁岁月 提交于 2019-12-23 07:10:12

问题


Consider the following code just as an example:

This one works

i = 0
flag = false
while i < 10
    flag = true
    if flag
        i+=1
    else
        break
    end
end

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

I get this errors:

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.


回答1:


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



回答2:


You shouldn't use break in a ternary here. It makes hard-to-read code. People don't usually expect control flow keywords in expressions. Actually, looking at it, it's not clear why you would even want to use ternary. Its two branches are completely unrelated.

If you're after clear compact code, consider using early break. Something like this:

while i < 10
  keep_processing = compute_flag # your logic here
  break unless keep_processing

  i += 1
end


来源:https://stackoverflow.com/questions/34135291/cant-use-break-in-the-false-part-of-the-ternary-operator-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!