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