Hi all
irb(main):001:0> "" || "asdf"
=> ""
irb(main):002:0> nil || "asdf"
=> "asdf"
irb(main):003:0>
I'd like the first one to also return "asdf". So is there an
operator
that fits my needs?
"" isn't false so || and or won't work. You'll have to code it
differently. E.g.:
a = "a string"
a || (a.empty? ? "asdf" : a)
This doesn't work for me. The previous one doesn't either. This one
does (I'm sure someone could easily clean this up, I feel lazy
though)...
[nil, "", "something"].each do |i|
puts( (item ||= "").empty? ? "asdf" : item )
There should be an additional closing ) on the previous line of code
Todd
I use these extensions in several projects for exactly the same reason
as the OP
class String
# Allowing a chain like: string_value.nonblank? || 'default value'
def nonblank?
self unless blank?
end
end
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
irb(main):018:0> "".nonblank? || "asdf"
NoMethodError: undefined method `blank?' for "":String
from (irb):4:in `nonblank?'
from (irb):18
Ok, so these are typically Rails projects, but you can take the
String#blank? extension from ActiveSupport
irb(main):019:0> class String #:nodoc:
irb(main):020:1> def blank?
irb(main):021:2> empty? || strip.empty?
irb(main):022:2> end
irb(main):023:1> end
=> nil
irb(main):024:0>
And then Joshua's orignal examples become:
irb(main):025:0* "".nonblank? || "asdf"
=> "asdf"
irb(main):026:0> nil.nonblank? || "asdf"
=> "asdf"
And for completeness:
irb(main):027:0> "jkl;".nonblank? || "asdf"
=> "jkl;"