3

In my Ruby program, I have an array of five strings, and I want to check if each one of the elements of that array match to a given requirement, for example:

a = ['', '', '', '']
a.inject(:blank?) # Will return true if (and only if) all elements of a are blank

I'm asking this question because Ruby has a pretty large standard API with a lot of pre-written syntactical sugar, which I want to know and don't want to reinvent.

2 Answers 2

15

There is a very concise way:

array.all? &:blank?

Study Enumerable and learn how to use Enumerators and you'll be speaking the most pleasant dialect of Ruby in no time.

2
  • 1
    Thank you, that's exactly what I wanted :D Apr 16, 2012 at 18:57
  • 1
    Note that blank? is not part of the Ruby core, and comes from ActiveSupport's core extensions (which are included in Rails). Apr 16, 2012 at 19:57
0

Just an alternative way: if you have String#to_proc (search it because I would not post my own depository site in case being considered as ads), you can use a similar way you have:

a.inject(&'&& $1.blank?')

which is equivalent to

a.inject{ |sum,i|
  sum && i.blank?
}
1
  • 1
    Generally speaking, it is fine to post your own projects if they happen to provide a relevant answer to the question. There are many discussions about this on meta, read them if you want to know more about the etiquette. Apr 16, 2012 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.