0

Let us say that I have this string:

bar="hello kohello hello"

I would like a function foo that I give it

foo(bar,"hello")

And get:

[0,8,14]

Now, I could just do (1 of many options):

def foo(str1,substr)
  i= -1
  substr_length = substr.length()
  str1.chars.map{ | char |
    i+=1
    str1(i,substr_length) == substr ? i : nil
  }.select{ |x| x }
end

Is there something more "Ruby like"? Also with Regexp, rather than strings.
Thanks.

user1134991
  • 3,003
  • 2
  • 25
  • 35

1 Answers1

0

In irb

arr = []
bar.scan("hello"){arr.push($~.offset(0)[0])}

now check arr

[0,8,14]

Adding my consoles' code for clarity

1.9.3-p362 :008 > arr = []
 => [] 
1.9.3-p362 :009 > bar.scan("hello"){arr.push($~.offset(0)[0])}
 => "hello kohello hello" 
1.9.3-p362 :010 > arr
 => [0, 8, 14] 

for those who dont know this cryptic ruby global variable.

$~ contains the MatchData from the previous successful pattern match. so it is similar to Regexp.last_match

for finding the index, we can find the Regexp.last_match.offset(0)[0]

aelor
  • 10,892
  • 3
  • 32
  • 48