1

This code is supposed to add the indices of the word 'hello' to the indices array, but it's not adding them to the array:

words = %w(hello how are you then okay then hello how) def global(arg1, arg2) indices = [] arg1.each do |x, y| indices << y if arg2 == x end indices end global(words,'hello') #=> [nil, nil] 

What's wrong with my code?

4
  • 1
    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 mean if arg2 == x? Commented Aug 4, 2017 at 6:29
  • 4
    If you had better, more descriptive names for your arguments, this bug wouldn't have happened. Commented Aug 4, 2017 at 6:30
  • 3
    Also, each_with_index instead of each. Commented Aug 4, 2017 at 6:32
  • 1
    Following on Sergio's comment: with each you can only access the value, not the index, so y will always be nil; each_with_index will give you the value and the index (in that order). Commented Aug 4, 2017 at 6:40

2 Answers 2

5

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 
Sign up to request clarification or add additional context in comments.

Comments

2
def indices(words, searched_word) words.each_with_index.select { |word, _| word == searched_word }.map(&:last) end words = %w(hello how are you then okay then hello how) indices words, 'hello' # => [0, 7] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.