Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of string scan results in ruby

Tags:

indexing

ruby

I want to get the index as well as the results of a scan

"abab".scan(/a/)

I would like to have not only

=> ["a", "a"]

but also the index of those matches

[1, 3]

any suggestion?

like image 976
adn Avatar asked Aug 19 '10 09:08

adn


People also ask

Can you index a string in Ruby?

The string. index() method is used to get the index of any character in a string in Ruby. This method returns the first integer of the first occurrence of the given character or substring.

How do you find the part of a string in Ruby?

A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.

What is an index in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found. Syntax: str.index()

What does =~ mean in Ruby?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.


1 Answers

Try this:

res = []
"abab".scan(/a/) do |c|
  res << [c, $~.offset(0)[0]]
end

res.inspect # => [["a", 0], ["a", 2]]
like image 192
Todd Yandell Avatar answered Sep 19 '22 03:09

Todd Yandell