educative.io

Educative

Validate integer

Shouldn’t I validate num to be an Integer?

p [1, 2, 3.4, 4, 5].collect { |number| number.is_a?(Integer) && number.even? }
[false, true, false, true, false]

Course: https://www.educative.io/collection/10370001/5658174447157248
Lesson: https://www.educative.io/collection/page/10370001/5658174447157248/5730161353818112

Hello @Aldo_Escudero
Yes, it’s a good practice to validate that the elements in the array are integers before checking if they are even. In your example, you can see that element 3.4 is not an integer, so it will return false when checking if it’s even.
But the example is given in the lesson:
input_array contains [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output is [2, 4, 6, 8, 10]
We are assuming that the given data array has only integers. So we don’t have to check whether the given data array has integers.
I hope this will help.
Happy Learning.

2 Likes