I am trying to select elements from an array:
arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
whose index is the Fibonacci number. I want to get the result:
['a', 'b', 'c', 'd', 'f', 'i', 'n']
My code returns both an element and an index.
def is_fibonacci?(i, x = 1, y = 0) return true if i == x || i == 0 return false if x > i is_fibonacci?(i, x + y, x) end arr.each_with_index.select do |val, index| is_fibonacci?(index) end
This code returns:
[["a", 0], ["b", 1], ["c", 2], ["d", 3], ["f", 5], ["i", 8], ["n", 13]]
Please help me understand how I can still iterate over an array and evaluate an index, but only return it.