I wrote a method to get the next element after a given element inside an array. If I provide the method with c, I want it to return e; if e, I want it to return a, etc.:
array = %w[a f c e]
def find_element_after(element, array)
index = array.find_index(element) + 1
array.at(index)
end
array.find_element_after("c", array)
If I pass in the last element I will get nil. But I want to return the first element instead.
I can solve this with if and else. But I want to know if Ruby has better way?
arraygrows in size because you are using a linear search. Instead I'd probably use some sort of linked-list or a hash inside a custom class that manages/maintains that hash. The key is what you search for and the value is the next element. That would be a very consistent lookup speed with a little slower insertion time.