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

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

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

···

On Sep 10, 5:25 pm, Summercool <Summercooln...@gmail.com> 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 ?

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 10, 4:34 pm, Philip Hallstrom <r...@philip.pjkh.com> wrote:

foo = foo.to_i + 1

would work as nil.to_i == 0

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 11, 2007, at 2:05 AM, Summercool wrote:

On Sep 10, 4:34 pm, Philip Hallstrom <r...@philip.pjkh.com> 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...