I'm using in my opinion trivial code, like this one
loop do
i++
break if i > 5
end
but when I try to run I'll get void value expression break if i > 5
what am I doing wrong? What does this error mean?
I'm using in my opinion trivial code, like this one
loop do
i++
break if i > 5
end
but when I try to run I'll get void value expression break if i > 5
what am I doing wrong? What does this error mean?
i = 0
loop do
i += 1
break if i > 5
end
What makes you think i++
on its own is valid Ruby code?
Although Ruby syntax is often easy to guess, don't assume it resembles other language constructs.
Ruby also has much better patterns to do things. My second example is an example of what you want.
i = 0
loop do
i = i + 1 # or shorthand i += 1
puts i
break if i > 5
end
In reality this counts to 6. Your break
should be at the beginning.
A better way
1.upto 5 do |i|
puts i
end
This counts to 5.
i++
may be perfectly valid. For example,
1++ 3
#=> 4
1++
3
#=> 4
That's because both of these expressions are parsed to
1 + +3
and then to
1 + 3
#=> 4
Your expression is therefore equivalent to
loop do
i + (break if i > 5)
end
A void value
exception was raised because break if i > 5
does not return a value.
You want
i = 0
loop do
i += 1
break if i > 5
end
i #=> 6
or (my preference)
i = 0
loop do
i += 1
raise StopIteration if i > 5
end
i #=> 6
Kernel#loop handles the StopIteration
exception by breaking out of the loop.