From: Phrogz Date: 2007-09-11T08:40:06+09:00 Subject: Re: is there a one liner to initialize a variable to 1, or increment by 1? On Sep 10, 5:25 pm, Summercool 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