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
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
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.
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
.