1

I'm new to Ruby, here's my problem : I would like to iterate through either an Array or String to obtain the index of characters that match a Regex.

Sample Array/String

 a = %q(A B A A C C B D A D)
 b = %w(A B A A C C B D A D)

What I need is something for variable a or b like ;

#index of A returns;
[0, 2, 3,8]

#index of B returns
[1,6]

#index of C returns
[5,6]
#etc

I've tried to be a little sly with

z = %w()

a =~ /\w/.each_with_index do |x, y|

 puts z < y

end

but that didn't workout so well. Any solutions ?

2
  • When you say that it "didn't work out so well", can you please describe how so? Commented Apr 14, 2014 at 7:48
  • 1
    I get a each_with_index method undefined for MacthData object error Commented Apr 14, 2014 at 7:52

3 Answers 3

3

For array, you could use

b.each_index.select { |i| b[i] == 'A' }

For string, you could split it to an array first (a.split(/\s/)).

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way of iterating through the Array instead of naming each character by hand?
@user3437917 What do you mean by naming each character by hand?
e.g for this answer, the A in the block was named. I would like to do the same of the B character without having to write a new block of code for B - or maybe I just didn't understand the code - I should try it first- newbie:)
1

If you want to get each character's index as a hash, this would work:

b = %w(A B A A C C B D A D)

h = {}
b.each_with_index { |e, i|
  h[e] ||= []
  h[e] << i
}
h
#=> {"A"=>[0, 2, 3, 8], "B"=>[1, 6], "C"=>[4, 5], "D"=>[7, 9]}

Or as a "one-liner":

b.each_with_object({}).with_index { |(e, h), i| (h[e] ||= []) << i }
#=> {"A"=>[0, 2, 3, 8], "B"=>[1, 6], "C"=>[4, 5], "D"=>[7, 9]}

Comments

0

If you want to count occurrences of each letter you can define helper method:

def occurrences(collection)
  collection = collection.split(/\s/) if collection.is_a? String

  collection.uniq.inject({}) do |result, letter|
    result[letter] = collection.each_index.select { |index| collection[index] == letter }
    result
  end
end

# And use it like this. This will return you a hash something like this: 
# {"A"=>[0, 2, 3, 8], "B"=>[1, 6], "C"=>[4, 5], "D"=>[7, 9]}
occurrences(a)
occurrences(b)

This should work either for String or Array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.