nil_or_empty? on String

C

Chris Morris

I just threw down the following -- it smells like I'm over-complicating
matters here. Is there a more elegant to do this?

if (user.nil_or_empty?) && (!pswd.nil_or_empty?)
raise 'cannot specify pswd without specifying user'
end

class String
def nil_or_empty?
empty?
end
end

class NilClass
def nil_or_empty?
nil?
end
end

I wanted to avoid this:

if (user.nil? || user.empty?) && !(pswd.nil? || pswd.empty?)

...which I guess isn't that bad now that I read it, although
nil_or_empty? will come in handy if I need to re-use it a lot.

--

Chris
http://clabs.org/blogki
-=-=-=-=-=-=-=-=-=-=-=-=-=-
Free solo piano album (mp3)
http://cministries.org/cstudios/blackandwhite.htm
 
C

Chris Morris

But more pragmatically, I think I would write:

if pswd.to_s != "" and user.to_s == ""
I think I will, too. My nose was correct. Thx for the virtual pairing :)

Chris
 
M

Martin DeMello

Brian Candler said:
We can assume that 'false' is also an invalid value for username/ password -
since false.empty? raises an exception - in which case,

if pswd && !pswd.empty? && (!user || user.empty?)

if [user, pswd].any? {|i| i.nil? || i.empty?}

or, if you want to be terse at the expense of readability

unless [user, pswd].any? {|i| i && i[0]}

or even

if [user, pswd].compact.mapf:)empty?).any?

where mapf is defined in http://www.rubygarden.org/ruby?AutoMap

martin
 
J

Jason Creighton

I wanted to avoid this:
if (user.nil? || user.empty?) && !(pswd.nil? || pswd.empty?)

You could do something like:

if user.to_s.empty? && pswd.to_s.empty?

Jason Creighton
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top