Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby/Rails have a ++ equivalent?

I guess I just got used to saying things like:

x++

in PHP and Java land. But when I tried this in my Rails code it had a fit:

compile error
/users/gshankar/projects/naplan/app/views/answers/new.html.haml:19: syntax error, unexpected ';'
/users/gshankar/projects/naplan/app/views/answers/new.html.haml:23: syntax error, unexpected kENSURE, expecting kEND
...}\n", 0, false);_erbout;ensure;@haml_buffer = @haml_buffer.u...
                              ^
/users/gshankar/projects/naplan/app/views/answers/new.html.haml:26: syntax error, unexpected $end, expecting kEND

I googled around a bit for Ruby/Rails operators for a reference to ++ but couldn't find anything. For a language which focuses on writing less I find it a bit strange that there wouldn't be a ++ equivalent. Am I missing something?

like image 289
Ganesh Shankar Avatar asked Feb 24 '10 00:02

Ganesh Shankar


4 Answers

Try this:

x += 1
like image 179
Trevor Avatar answered Oct 04 '22 00:10

Trevor


x+=1 is the best you can do in Ruby.

For a detailed explanation, see Why doesn't Ruby support i++ or i--​ (increment/decrement operators)?

like image 40
igul222 Avatar answered Oct 03 '22 23:10

igul222


Really you should be asking yourself why you need increment/decrement. I've been using Ruby for close to two years now, and hadn't noticed that increment and decrement operators were missing. Might be because the Ruby way to do operations where increment and decrement operators are commonly used is with an iterator.

Such as each_with_index which executes a given block for each element/index pair in the array.

For example, this code will iterate through an array outputting the string representation fo each element and the parity of its index.

array = ["first", "second", "third","fourth","last"]
array.each_with_index do |object,index|
   puts index % 2 ? "even" : "odd"
   puts object.to_s
end

Edit: Removed Fixnum extension providing postfix increment because it doesn't work. Upon closer inspection there's nothing stopping you from adding it, but it would involve writing your feature in C, and a recompile.

like image 40
EmFi Avatar answered Oct 04 '22 00:10

EmFi


You have to use x+=1 instead.

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators

like image 23
thebretness Avatar answered Oct 04 '22 00:10

thebretness