views:

243

answers:

5

A long time ago I saw this trick in Ruby. Instead of doing (for example)

if array1.empty? and array2.empty? and array3.empty?

You could call all of the objects at once and append the operation at the end, kind of like

if %w(array1 array2 array3).each { |a| a.empty? }

But I think it was simpler than that... or, it could be that. I really don't know, but that's why I'm interested in finding out. Thanks.

+8  A: 

if [array1, array2, array3].all? { |a| a.empty? }

I think that's what you're looking for

J Cooper
+1  A: 

J Cooper has it right, but just to add a footnote:

%w(array1 array2 array3) # => ["array1", "array2", "array3"]

%w takes a string and splits it on whitespace to return you an array of strings

Gareth
+3  A: 

You can use Symbol#to_proc, if you are using Rails or Ruby 1.9:

[array1, array2, array3].all?(&:empty?)
Milan Novota
A: 

On a side note, Symbol#to_proc can have performance issues, so use it in cases when readability is worth it.

krusty.ar
A: 

Review enumerable documentation and you will find such methods.

Abdelrahman