is there a one liner to initialize a variable to 1, or increment by 1?

S

Summercool

as we can use
foo ||= Cart.new
so that if foo is nil, then now foo = Cart.new

but let's say if I have a variable i want to increment by 1
is there an idiomatic and elegant way to say

foo += 1, unless foo is nil, then set it to 1 ?

maybe
foo = (foo == nil ? 1 : foo + 1)

but it is kind of long and not readable
 
P

Philip Hallstrom

as we can use
foo ||= Cart.new
so that if foo is nil, then now foo = Cart.new

but let's say if I have a variable i want to increment by 1
is there an idiomatic and elegant way to say

foo += 1, unless foo is nil, then set it to 1 ?

foo = foo.to_i + 1

would work as nil.to_i == 0
 
P

Phrogz

but let's say if I have a variable i want to increment by 1
is there an idiomatic and elegant way to say

foo += 1, unless foo is nil, then set it to 1 ?

Usually I am doing this sort of thing in a Hash or Array, where the
default value is your friend:
counts = Hash.new(0) # or Array.new(0), depending on need
...later...
counts[ my_var ] += 1

But, to answer your question specifically, I'd probably do a non-one-
liner:
foo ||= 0
foo += 1
or (like yours, if I was feeling cheeky):
foo = foo.nil? ? 1 : foo + 1
 
S

Summercool

foo = foo.to_i + 1

would work as nil.to_i == 0

I think it was also in Perl that $foo++ will work if $foo is not
defined, then it will be just treated as 0.
but if "use strict" then it won't work... but the code is more robust
that way

so Ruby is like it will impose the strict for code robustness...
 
X

Xavier Noria

I think it was also in Perl that $foo++ will work if $foo is not
defined, then it will be just treated as 0.
but if "use strict" then it won't work...

It works with strictness on as well. You need to declare the
variable, that's the bit strict.pm adds here:

$ perl -Mstrict -wle 'my $foo; ++$foo; print $foo'
1

See, $foo is undef when it is incremented.

-- fxn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top