Returning all indices from array with match

I’m really struggling with this one, and I don’t understand it. It just
doesn’t behave the way I expect, so I’m obviously misunderstanding
something.

Assume I have an array like this:

aa = %w( BB39 FF24 AB67 FF90 GH40 )

I simply want to return all the indices where I’m matching the contents
of the array.

I’ve tried all sorts of varieties of this kind of thing:

aa.each_with_index{ |x,i| puts x } # No matching criteria
0
1
2
3
4

But I throw in a match, it just won’t work (returns nothing):

aa.each_with_index{ |x,i| puts x if i =~ /^[“FF”]/ } # Use matching

Why isn’t this returning the following?:
1
3

And what solution would y’all suggest for this simple problem of
returning all array indices based upon a element match?

Thomas L. wrote in post #1179206:

I’m really struggling with this one, and I don’t understand it. It just
doesn’t behave the way I expect, so I’m obviously misunderstanding
something.

Assume I have an array like this:

aa = %w( BB39 FF24 AB67 FF90 GH40 )

aa.each_with_index{ |x,i| puts x if i =~ /^[“FF”]/ } # Use matching

Why isn’t this returning the following?:
1
3

aa.each_with_index.select { |x,i| x =~ /^FF/ }.map(:last)
or
aa.each_with_index.each_with_object([]) { |(x,i),a| a << i if x =~ /^FF/
}

aa.each_with_index{ |x,i| puts x if i =~ /^[“FF”]/ }
should be :
aa.each_with_index{ |x,i| puts i if x =~ /^[“FF”]/ }

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs