ORing of strings

Hi,

I wanted to do this: get display_name as one of those nick_name, first and last in that order. @display_name = @nick_name || @first_name || @second_name

but if nick_name turns out be "" and not ni. so @display_name gets "" and not the values in first or second.

How do we handle this situation?

Regards, Sandeep G

I handle this by creating a String#nonblank? to work like Numeric#nonzero? (see docs)

class String    # Allowing a chain like: string_value.nonblank? || 'default value'    def nonblank?      self unless blank?    end end

and to duck-type when nil:

class NilClass    # Allowing a chain like: value.nonblank? || 'default value'    def nonblank?      self    end    # so it plays nicely with Numeric#nonzero?    def nonzero?      self    end end

Then your example becomes:

@nick_name = nil @first_name = "" @second_name = "Sandeep"

>> @display_name = @nick_name.nonblank? || @first_name.nonblank? || @second_name.nonblank? => "Sandeep"

You can actually leave the .nonblank? off of the last part if you don't care nil v. '' depending on @second_name.

-Rob

Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com