josethernandezc
josethernandezc

Reputation: 160

Rails 3 to_i method susbtitute

I have a string variable codigo = "0001" that I want to convert to an integer and increment its value by 1, I used to do this with codigo.to_i += 1 but apparently that method has been deprecated in Rails 3. Which is the Rails 3 way to do this now?

Upvotes: 0

Views: 1922

Answers (1)

MrTheWalrus
MrTheWalrus

Reputation: 9700

The basic problem here is that your variable, codigo, is a String.

codigo.to_i will return an integer, but it doesn't change the type of the variable it's called on, so it's still a String, you've just called a method on it that returns an integer.

codigo.to_i + 1 would return 2.

codigo.to_1 += 1 will produce an error because the return value isn't in any variable, so it can't be incremented.

So, to convert the variable to an integer and increment that, do this:

codigo = codigo.to_i
codigo += 1

If it makes more sense, you can also do this in one line:

codigo = codigo.to_i + 1

Upvotes: 4

Related Questions