lkahtz
lkahtz

Reputation: 4796

Can I define my own "if any" syntax in ruby?

I constantly write something like:

val if val && !val.empty?

Can I define this syntax more concisely to something like:

val if_any 

or

val if any

?

Upvotes: 0

Views: 150

Answers (3)

thorncp
thorncp

Reputation: 3627

A slight variation of the Object method that returns the actual value.

class Object
  def if_any?
    self if self && (!self.respond_to?(:empty?) || !self.empty?)
  end
end

[].if_any? # => nil
[42].if_any? # => [42]

"".if_any? # => nil
"hi".if_any? # => "hi"

# and for the objects that don't define #empty?
nil.if_any? # => nil
42.if_any? # => 42
false.if_any? # => nil
true.if_any? # => true

Edit: Hmm, after looking at this again, I think I wouldn't use a question mark in the method name, as it goes against ruby convention of returning boolean.

Upvotes: 1

Todd Yandell
Todd Yandell

Reputation: 14696

No, I don’t believe Ruby allows you to extend the syntax that way. The closest you could get is adding a method to Object:

class Object
  def any?
    !!self && !self.empty?
  end
end

"hi".any? # => true
[].any?   # => false
nil.any?  # => false

if x.any?
  # do something
end

Upvotes: 2

Spyros
Spyros

Reputation: 48636

There is val.blank?

irb(main):008:0> ''.blank?
=> true
irb(main):009:0> '   '.blank?
=> true
irb(main):010:0> nil.blank?
=> true
irb(main):011:0> false.blank?
=> true
irb(main):012:0> 'whatever'.blank?
=> false

Upvotes: 4

Related Questions