I am trying to select elements out of an array:
arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
whose index is a Fibonacci number. I want the result:
['a', 'b', 'c', 'd', 'f', 'i', 'n']
My code returns both the element and the 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 through the array and evaluate the index but only return the element.
The filter() is an inbuilt method in Ruby that returns an array which contains the member value from struct which returns a true value for the given block.
Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object. Here, A is the initialised object. Parameters: This function does not accept any parameters. Returns: the value of the given object.
index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found.
You can change the last bit of your code to
arr.select.with_index do |val, index|
is_fibonacci?(index)
end
This works because if you call a method such as select
without a block, you get an Enumerator
object, on which you can then chain more Enumerable methods.
In this case I've used with_index
, which is very similar to calling each_with_index
on the original array. However because this happens after the select
instead of before, select
returns items from the original array, without the indices appended
Your code seems great so far, I wouldn't change it. You can go over your results after the fact and change the [element, index]
pairs to only contain the element
by mapping over each pair and only taking the first:
>> results = [["a", 0], ["b", 1], ["c", 2], ["d", 3], ["f", 5], ["i", 8], ["n", 13]]
>> results.map(&:first)
=> ["a", "b", "c", "d", "f", "i", "n"]
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