How to do it Ruby way: Count no. the presence of a in b

This is the piece of code I'm using now:

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

      

Is there any Ruby function that does this? Any functional equivalent? Or is there anything better?

+2


source to share


4 answers


If a and b are strings:



b.scan (a) .length
+9


source


The most obvious way

enum.find_all {| obj | block } => array

      

a plus



array.length

      

or you can just do it with a fold

enum.inject {| memo, obj | block } => obj

      

+4


source


I am assuming that b

is an array and b

is an object to look for in the array.

ary = ["foo", "bar", "baz", "foo", "foo", "maz"]
look_for = "foo"

p a.detect {|i| i == look_for }.length
# => 3

      

You can also disable it in Array

.

class Array
  def occurrences_of(object)
    detect {|i| i == object }.length
  end
end

p ["foo", "bar", "baz", "foo", "foo", "maz"].occurrences_of("foo")
# => 3

      

+3


source


You just have to loop through the array using each and create an array with the key "a" through that and count as a value. Then just return the bill.

def count_occurences(a, b)
  r = Array.new
  b.eachdo |e|
    if e == a 
      r[e]++
    end
  end
end

      

This should do it!

-2


source







All Articles