Pergunta

Example:

my_array = ['2823BII','4A','76B','10J']

[using magical method delete_if_doesnt_contain()]

my_array.map! do |elements|
    elements.delete_if_doesnt_contain('A')
end

I want that to set my_array = ['4A']

Even if I could iterate through an array and just return the index of the element that contains an 'A' I'd be happy. Thanks for any help!

Thanks for the answers below, but one more question.

other_array = ['4']
my_var = other_array.to_s
my_array.select!{|x| x.include?(my_var)}

This isn't working for me. What am I missing? Something happen when I converted the array to a string?

Foi útil?

Solução

Very easy using #select :

my_array = ['2823BII','4A','76B','10J']
my_array.select { |str| str.include?('A') }
# => ["4A"]

Or if you want to modify the source array, do use the bang version of select :-

my_array.select! { |str| str.include?('A') }

Outras dicas

Arup's answer is correct.

However, to answer your last question specifically, "iterate through an array and just return the index of the element that contains an 'A'", the "index" method returns the index for a matching element:

my_array.index {|x| x.include?('A') }

The grep method is a lot shorter

my_array = ['2823BII','4A','76B','10J']
my_array.grep /A/
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top