From: Belorion Date: 2005-07-26T00:22:26+09:00 Subject: Re: Newby question 'unless' On 7/25/05, EdUarDo wrote: > Hi all, I'm overriding to_s method and I want to > print an attribute if a condition is fulfilled. > > def to_s > "#{@a}" + "#{@b}" unless @a == 0 > end > > That sentence doesn't print anything when @a == 0 but what I want to do > is to not print @b when @a == 0. > > What's the correct syntax? > > I know I could do: > > def to_s > s = "\n#{@post}" > if @post != :GK > s += "#{@side}" > end > s > end You could try the ternary operator: def to_s @a == 0 ? "#{@a}" : "#{@a} #{@b}" end Or, def to_s s = @a s << " #{@b}" unless @a == 0 return s end end