Conditionals give you nil when they're not met, and nil.to_s is an
empty string, so you don't have to specify a literal empty string in
cases like this. I would refactor your second line to:
"#{@a}" + ("#{@b}" unless @a.zero?)
at which point you can make it nicer by getting rid of the parens and
the + :
"#{@a}#{@b unless @a.zero?}"
That gives you a closer lexical mapping between what you're asking for
and how the eventually string will read ("@a@b?", one might say).
Conditionals give you nil when they're not met, and nil.to_s is an
empty string, so you don't have to specify a literal empty string in
cases like this.
Sure, but not in the case I posted:
def to_s
"#{@a}" + (@a == 0 ? "" : "#{@b}" )
end
-:4:in `+': cannot convert nil into String (TypeError)
from -:4:in `to_s'
from -:8
"#{@a}#{@b unless @a.zero?}"
This is indeed much better. Thanks for your advice - I can see my ruby
skills getting better every day.
Conditionals give you nil when they're not met, and nil.to_s is an
empty string, so you don't have to specify a literal empty string in
cases like this.
Sure, but not in the case I posted:
def to_s
"#{@a}" + (@a == 0 ? "" : "#{@b}" )
end
-:4:in `+': cannot convert nil into String (TypeError)
Whoops, I thought I was being helpful by showing an intermediate step
but indeed that + nil would not work