Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

loops

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?

like image 640
noircc Avatar asked Aug 28 '12 12:08

noircc


People also ask

How do I check if an array contains something in Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

How do you check if an array element is a number?

To check if an array contains only numbers:Use the Array. every() method to iterate over the array. On each iteration, check if the type of the current element is number . The every method will return true if the array contains only numbers and false otherwise.


1 Answers

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
like image 111
Sergio Tulentsev Avatar answered Sep 23 '22 15:09

Sergio Tulentsev