Ruby If .. Else .. End / Increment: Syntax error

I created a class method that iterates through an array of Order objects. I use the data from there to create a hash. One of my if blocks is inside iterable:

if !(report_hash[user_id][reason])
    report_hash[user_id][reason] = 1
else
    report_hash[user_id][reason]++
end

When I run this method, I get:

 .rb:66 syntax error, unexpected keyword_end (SyntaxError)

Line 66 is where it is end. Why doesn't Ruby expect the end of this block to end? I plan to move all the conditional logic into separate class methods when everything works, but I tried to figure it out and got a little stuck.

+3
source share
2 answers

The increment++ method is not legal in Ruby , use += 1:

if !(report_hash[user_id][reason])
    report_hash[user_id][reason] = 1
else
    report_hash[user_id][reason] += 1
end

( ): :

report_hash[user_id][reason] ||= 1 # this will set report_hash[user_id][reason] to 1 if it is nil
report_hash[user_id][reason] += 1
+6

Ruby ++. :

report_hash[user_id][reason] += 1
+1

All Articles