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.
There is syntax issue in your code. You can't use
if
in ternary operator?:
as can be seen in your code lineif 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.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: