2017-08-04 6 views
0

このコードはindices配列に単語'hello'のインデックスを追加することになっているが、それは、配列に追加していない:配列内の特定の要素のすべてのインデックスを見つける方法は?

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] 

私のコードで何が悪いのでしょうか?

+1

'ARG1 == X 'もし配列はその要素の1つと等しくないので、この条件は決して真ではありません。だからこそあなたは指数を得ていません。 'もしarg2 == x'を意味しましたか? –

+4

あなたの引数の方がわかりやすく、説明的な名前があれば、このバグは起こりませんでした。 –

+3

また、 'each'の代わりに' each_with_index'を使います。 –

答えて

4

他の方法で猫をスキンケアすることができます。

トラバース​​とselect要素検索語と一致するもの:

def indices(words, searched_word) 
    words.each_index.select { |index| words[index] == searched_word } 
end 

トラバース各ワードに沿って、そのインデックス(each_with_index)とし、単語が一致する場合、明示的なindicesアレイ内のインデックスを格納します。次いでindicesアレイ返す:上記のように

def indices(words, searched_word) 
    indices = [] 
    words.each_with_index do |word, index| 
    indices << index if word == searched_word 
    end 
    indices 
end 

同じ、しかし(また、その配列が返される)with_objectを介して右の反復中に明示的に配列を渡す:

def indices(words, searched_word) 
    words.each_with_index.with_object([]) do |(word, index), indices| 
    indices << index if word == searched_word 
    end 
end 
1
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] 
関連する問題