0
require 'csv'

i = 0
CSV.foreach("survdata.csv", headers: true) do |row|
  puts row
  i++
  if i > 1 then
    break
  end
end

This looks so simple, and yet it doesn't run. Can you see why I am getting:

/mydev/surveyresult/surveyresult.rb:11: void value expression
halfer
  • 19,824
  • 17
  • 99
  • 186
pitosalas
  • 10,286
  • 12
  • 72
  • 120

3 Answers3

1

Ruby doesn't have an increment operator the last time I looked.

In place of

i++

do

i += 1
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
1

Ruby does not support i++ syntax as a shortcut to i+=1. See "Why doesn't Ruby support i++ or i-- (increment/decrement operators)?" for more information why.

You can fix your code like this:

require 'csv'

i = 0
CSV.foreach("survdata.csv", headers: true) do |row|
  puts row
  i = i+1
  if i > 1 then
    break
  end
end

More information on the error message (thanks sawa):

Ruby does actually support i++ syntax. If it is followed by x, it is interpreted as unary operator + applied to x, whose result passed as an argument to i+. In your example, if i > 1 then; break; end does not return any value, hence the error message "void value expression".

Community
  • 1
  • 1
babgyy
  • 343
  • 1
  • 11
  • 2
    To be strict, your answer is wrong. If Ruby did not support such construct syntactically, then it would raise a syntax error, but it doesn't. It does support `i++` syntax. If it is followed by `x`, it is interpreted as unary operator `+` applied to `x`, whose result passed as an argument to `i+`. – sawa Mar 29 '16 at 16:27
  • Fair strict point. However there was no `x` here, can we agree to say it won't work as expected by the author ? – babgyy Mar 29 '16 at 16:34
  • `x` in this case is `if i > 1 then; break; end`. Furthermore, this does not answer the question why the OP is getting "void value expression". Along the lines of your answer, can you answer why it did not raise a syntax error? – sawa Mar 29 '16 at 16:35
0

Yes. It is because the:

if i > 1 then
  break
end

part breaks, which does not have a return value (within the code block in question). And you cannot apply the unary operator +@ to something that lacks a value, nor can i.+ take the return value of such as an argument.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    Why was this down voted? Despite the accepted answer has a clearer explanation this one is also correct. – xuuso Jun 30 '16 at 18:02