I've been going through the exercises at Ruby Monk and I'm having trouble deciphering one of the example solutions.
The problem (from this page) was:
Write a method that counts the number of elements of the array that is being passed in, only if the index of the number 42 in the one-dimensional representation of the array is 5.
My solution, which worked fine, was:
def zen(array)
converted_array = array.flatten.compact
converted_array.count if converted_array.index(42) == 5
end
Their solution was:
def zen(array)
converted = array.compact.flatten
converted.index(42) == 5 ? converted.count : nil
end
I understand everthing to the left of the :
in the second line of the method but after that I can't figure it out. I thought that compact
removes all nil values from an array?