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

Sandeep G. wrote:

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 dont really understand what you mean but why not put them in array :slight_smile:

@display_name = [“nick_name”, “asd”, “asd”]

and then

@display_name.each do |val|
if nil or if “” then do that or this?
end

On Sep 7, 2007, at 1:49 AM, Sandeep G. wrote:

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 B. http://agileconsultingllc.com
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs