Some other ways to skin the cat.
Traverse each_index and select the ones whose element match the searched word:
def indices(words, searched_word) words.each_index.select { |index| words[index] == searched_word } end
Traverse each word along with its index (each_with_index) and store the index in an explicit indices array if the word matches. Then return the indices array:
def indices(words, searched_word) indices = [] words.each_with_index do |word, index| indices << index if word == searched_word end indices end
Same as above, but pass the explicit array right into the iteration via with_object (which will also return that array):
def indices(words, searched_word) words.each_with_index.with_object([]) do |(word, index), indices| indices << index if word == searched_word end end
if arg1 == x- an array will never equal one of its elements, so this condition is never true. That's why you get no indices. Did you meanif arg2 == x?each_with_indexinstead ofeach.eachyou can only access the value, not the index, soywill always benil;each_with_indexwill give you the value and the index (in that order).