我有一根线

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

我要付款方式
"#Sachin|0|7;#Tendulkar|29|10;#Sachinn|63|7;"

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

这给了我
 "#Sachin|0|7;#Tendulkar|29|10;#Sachin|0|7;"

那么我如何得到每个子字符串的起始索引呢?

最佳答案

这实际上是一个非常重要的任务,在其他的问题中已经讨论过很多了这是最常见的解决方案:

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};"}

关于ruby-on-rails - 如何找出 ruby 中每场比赛的起点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17185943/

10-09 04:20