Is there a one liner to initialize a variable to 1, or incre

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

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

On Sep 10, 4:34 pm, Philip H. [email protected] wrote:

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…

On Sep 11, 2007, at 2:05 AM, Summercool wrote:

On Sep 10, 4:34 pm, Philip H. [email protected] wrote:

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…

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

On Sep 10, 5:25 pm, Summercool [email protected] wrote:

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs