11

I want a one-liner to return true/false, that tests each element in an array for whether it's an Integer or not. So if any element in the array is not an Integer, it should return false, else true. Here's my try:

>> ([2,1,4].map {|x| (x.is_a? Integer)}).reduce {|x, result| x and result}
=> true
>> ([2,"a",4].map {|x| (x.is_a? Integer)}).reduce {|x, result| x and result}
=> false

Any other ideas to distill it down further?

2 Answers 2

19
array.all?{ |x| x.is_a? Integer }
Sign up to request clarification or add additional context in comments.

Comments

4
ary.all?(&Integer.method(:===))

2 Comments

I really wish Ruby had a better syntax for accessing methods. This is more conceptually pure, but in practice actually longer than writing out the explicit block.
@Chuck: Yeah. There is an idea floating around which pops up every couple of years to make a better distintion between the . (message sending) and :: (scope resolution) operators. Currently, . means message sending and :: means scope resulotion or message sending. If we remove the "or message sending" part from ::, we can extend it to allow stuff like foo::bar to mean foo.method(:bar). Currently, that doesn't work, since foo::bar means the same as foo.bar.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.