views:

47

answers:

3

I want to use expression:

!([1,2,3] & [43,5]).empty?
=> false
!([1,2,3] & [3,5]).empty?
=> true

to check if two arrays contains at least one common value. And I wonder if there is a better way of doing it? Maybe something like:

 ([1,2,3] & [3,5]).non_empty?

How to write non_empty? method?

+3  A: 

Technically answered:

class Array
    def non_empty?
        !self.empty?
    end
end

puts [1].non_empty?

Though .any? already seems to exist for that purpose (see JHurra's answer)

Dario
Thanks, technicaly you answered this question, but @JHurrah answer is what I was looking for.
klew
+4  A: 
([1,2,3] & [3,5]).any?
JHurrah
Why this works: Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil.
ryeguy
Thanks, that's what I was looking for!
klew
+1  A: 

An equivalent query would be asking if the array is not blank. The equivalent to !array.blank? is array.present?

Check http://api.rubyonrails.org/classes/Object.html#M000280

Chubas
Thanks, but remember it is added in Rails, it's not Ruby.
klew