1

I want to pre-increment a variable value in ruby but i can't.

in java we can do this

int a=50;
++a;
System.out.println(a);

but how to do this in ruby ? if i do this it gives me error

a=50
1-=a
puts a
sourav das
  • 11
  • 2
  • 3
    What is the difference between pre-increment and post-increment in the Java code you posted? And how would you write that statement in Java, without using pre-increment? – axiac May 19 '21 at 14:18
  • I believe you are searching for this -> https://stackoverflow.com/questions/3717519/no-increment-operator-in-ruby – mahatmanich May 19 '21 at 14:18
  • 1
    Does this answer your question? [Why doesn't Ruby support i++ or i--​ (increment/decrement operators)?](https://stackoverflow.com/questions/3660563/why-doesnt-ruby-support-i-or-i-increment-decrement-operators) – mahatmanich May 19 '21 at 14:20
  • In short: There is no such thing in ruby, but nor do you really need it. You example code is pointless, as a "pre-" or 'post-" increment in that context would make zero difference. In ruby, you could write that as `a += 1`. – Tom Lord May 19 '21 at 14:47
  • 1
    `1-=a;` is not valid in either Java or Ruby. You can't have a literal on the left hand side of an "operator equal" assignment in either language. Try `a -= 1` for subtraction or `a += 1` for addition, as Tom Lord suggested. – pjs May 19 '21 at 15:02

2 Answers2

2

Use Ruby's Abbreviated Assignment

Ruby doesn't implement a ++ operator as such, either pre or post. However, you don't really need it, either. Since everything in Ruby is an expression, the following is idiomatic Ruby code that does what you likely expect in a more Ruby-centric way:

a = 50
p a+=1
#=> 51

This works because a+=1 increments the value of a, assigns the result back to a, and then returns the result. Under the hood, this is largely equivalent to writing:

a = 50
a = a + 1
Kernel.p(a)

but is shorter and easier to read because the abbreviated assignment is evaluated and passed as an argument to Kernel#p, where it's both sent to standard output and returned as a value.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
0

For the sake of completeness, here are equivalent pieces of code for pre- and post-increment.

Java:

public class PreProIncrement
{
   public static void main(String[] args)
   {
      int a = 50;
      System.out.println(++a);
      System.out.println(a);
      System.out.println(a++);
      System.out.println(a);
   }
}

Ruby:

a = 50
p(a = a + 1) # or p(a+=1)
p(a)
a = p(a) + 1
p(a)

Both have the same output:

51
51
51
52

In Ruby, p a is used instead of puts a because p a displays and returns a, while puts a displays a but returns nil.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124