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
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 to share