1

Let's say you have a list in Ruby:

integer_list = [1, 2, 3, 4, 5]

Selecting only the even numbers would be easy

integer_list.select(&:even?)

But what happens, if you had a mixed list? And wanted to select only the integers From what I've learned, I would write something like this:

mixed_list = [1, 2, 3, 4, 5, 'string']
mixed_list.select { |x| x.is_a? Integer }

My question now is, is there a way to shorten this code like in the first example? Roughly like that:

mixed_list.select(&:is_a? Integer)
Frank
  • 33
  • 7
  • What if you have def is_int?(x) x.is_a? Integer end; [1, 2, 3, 4, 5, 'string'].select(&method(:is_int?)) where defining a separate method to check if a given argument is an integer and call that method with the short hand mechanism. – Bunti Dec 22 '15 at 23:40
  • @Uri Agassi's answer to the [earlier question](http://stackoverflow.com/questions/23695653/can-you-supply-arguments-to-the-mapmethod-syntax-in-ruby) is a classic. – Cary Swoveland Dec 22 '15 at 23:55

0 Answers0