0

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?

Jakub Kohout
  • 1,854
  • 3
  • 21
  • 36

3 Answers3

2
i = 0
loop do
  i += 1
  break if i > 5
end
luckyruby
  • 273
  • 1
  • 7
2

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.

peter
  • 41,770
  • 5
  • 64
  • 108
1

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.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • Wow that's perfectly well explained. Thank you. Your answer provides the best explanation of my problem, why it is happening and how to avoid it. – Jakub Kohout Dec 18 '16 at 11:13