noircc noircc - 2 years ago 91
Ruby Question

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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download