noircc
noircc

Reputation: 640

Can i check if an array e.g. just holds integers in ruby?

Title, i think is self declaring. I am kind of a java-developer and wanna ensure that my array holds just integer values. I know everything in ruby is a object. I find it inconvenient to loop through the array and make checks at every element. Is there any shortcut to this in ruby?

Upvotes: 9

Views: 10420

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

Use Enumerable#all? with a block. Integer numbers are instances of class Integer in ruby.

[1, 2, 3].all? {|i| i.is_a?(Integer) } # => true
[1, 2, 3, '4'].all? {|i| i.is_a?(Integer) } # => false

Upvotes: 23

Related Questions