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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With