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
Jasim
source
to share
4 answers
If a and b are strings:
b.scan (a) .length
+9
James
source
to share
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
Steve gilham
source
to share
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
August Lilleaas
source
to share
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
Jamie Rumbelow
source
to share