Thursday, 1 March 2018

How to find out the starting point for each match in ruby




Say, i have a following string



string = "#Sachin is Indian cricketer. #Tendulkar is right hand batsman. #Sachin has been honoured with the Padma Vibhushan award "


I want o/p as



"#Sachin|0|7;#Tendulkar|29|10;#Sachinn|63|7;"



I tried following



 new_string = ""
string.scan(/#\S+/).each{|match| new_string+="#{match}|#{string.index(match)}|#{match.length};" }


which gives me



 "#Sachin|0|7;#Tendulkar|29|10;#Sachin|0|7;" 



So how i will get the starting index of each sub-string?


Answer



This is actually quite a non-trivial task, and has been discussed quite a bit in other questions on SO. This is the most common solution:



string = "#Sachin is Indian cricketer. #Tendulkar is right hand batsman. #Sachin has been honoured with the Padma Vibhushan award "
new_string = string.to_enum(:scan,/#\S+/i).inject(''){|s,m| s + "#{m}|#{$`.size}|#{m.length};"}

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...