怎么做Ruby方式:数不.b的出现

Jas*_*sim 2 ruby

这是我现在使用的代码片段:

def countOccurences(a, b)
  #counts the number of occurences of a in b 
  count=0
  cur=0
  while cur < b.length do
    temp=b.index(a, cur)
    if temp == nil
      break
    end
    count=count+1
    cur=temp+a.length
  end
  return count
end
Run Code Online (Sandbox Code Playgroud)

是否有任何Ruby功能可以做到这一点?任何功能等同?还是更好的?

Jam*_*mes 9

如果a和b是字符串:

b.scan(a).length