Combine @item.foo.nil? || @item.foo.empty? ?

J

Joe Ruby

I have code like this in my (Markaby) templates:

tr do
td @item.foo
end unless (@item.foo.nil? || @item.foo.empty?)

Is there a way to combine these two OR clauses into one?

tr do
td @item.foo
end unless @item.foo.nil_or_empty?

Thanks,
Joe
 
M

Matthew Moss

tr do
td @item.foo
end unless (@item.foo.nil? || @item.foo.empty?)

Is there a way to combine these two OR clauses into one?


Define a method on the class of foo?

class Foo
def nil_or_empty?
return nil? || empty?
end
end
 
J

Joel VanderWerf

Matthew said:
Define a method on the class of foo?

class Foo ^^^
Object
def nil_or_empty?
return nil? || empty?
end
end

Otherwise it won't be defined when foo==nil.
 
A

ara.t.howard

I have code like this in my (Markaby) templates:

tr do
td @item.foo
end unless (@item.foo.nil? || @item.foo.empty?)

Is there a way to combine these two OR clauses into one?

tr do
td @item.foo
end unless @item.foo.nil_or_empty?

Thanks,
Joe

tr{ tr @item.foo } unless @item.foo.to_s.empty?

-a
 
A

ara.t.howard

It makes sense to me that

object.to_s.empty? # => true

should imply

object.empty? # => true

So why not just do

class NilClass
def empty?; true; end
end

?

-Marshall



def deep_in_some_other_unrelated_code
begin
should_always_be_empty = buggy_method

abort unless should_always_be_empty.empty? # OOPS!

transfer_four_million_euros_to_swiss_account
rescue
hours_of_debugging?
ensure
modify_builtins_with_care!
end
end



-a
 
L

Logan Capaldo

It makes sense to me that

object.to_s.empty? # => true

should imply

object.empty? # => true
Doesn't to me. nil is not a container, and it should not be treated
as one. A string is a container (contains a sequence of characters)
and can therefore be empty. The fact that one, arbitrary string
representation of nil happens to be the empty string doesn't mean
that nil is empty. (This is also why I disklike rails's #blank?, but
at least it's named something different.)
 
F

Farrel Lifson

I have code like this in my (Markaby) templates:

tr do
td @item.foo
end unless (@item.foo.nil? || @item.foo.empty?)

Is there a way to combine these two OR clauses into one?

tr do
td @item.foo
end unless @item.foo.nil_or_empty?

Thanks,
Joe

tr do
td @item.foo
end unless Array(@item).empty?
 
A

Austin Ziegler

class NilClass
def empty?; true; end
end

Because nil isn't empty.

It isn't a container. It's not an array, hash, or string.

Rails has a #blank? method -- which I've used this weekend -- but
nil.empty? is a false question.

-austin
 

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,733
Messages
2,569,440
Members
44,829
Latest member
PIXThurman

Latest Threads

Top