Reputation: 480
This is the snippet 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 anything better?
Upvotes: 2
Views: 798
Reputation: 5095
You just need to loop through the array using each, and through that create an array with the key of "a" and count as a value. Then just return the count.
def count_occurences(a, b)
r = Array.new
b.eachdo |e|
if e == a
r[e]++
end
end
end
That should do it!
Upvotes: -2
Reputation: 54593
I'm assuming 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 could also monkey-patch this into 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
Upvotes: 3
Reputation: 11277
The most obvious way
enum.find_all {| obj | block } => array
plus
array.length
or you could just do it with a fold
enum.inject {| memo, obj | block } => obj
Upvotes: 4