tags:

views:

150

answers:

4

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?

+4  A: 

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
Steve Gilham
@Steve: I'll have to explore enum. Thanks for the tip.
Jasim
+3  A: 

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
August Lilleaas
A: 

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!

Jamie Rumbelow
Couple of things wrong with this one: a) You're missing a space between "each" and "do". b) Ruby does not have a `++` operator. c) The return value of that method will always be `b` - you probably want to return `r[a]`. c) `r[e]` will only work if e is an integer, so a has to be an integer for this to work. d) Note that elements of r will be initialized to nil, not 0, so incrementing will only work if you initialize to 0 first. e) Since you only access `r[e]` when e==a, you`re only ever accessing one index of r so you could as well use a single integer for counting instead of an array.
sepp2k
+8  A: 

If a and b are strings:

b.scan(a).length
James
Yes! That did it. Thank you.
Jasim
@Jasim: Then you should accept James' answer so he (and you) can get credit.
Chuck
@Chcuk: Yeah I accepted. Thanks for the info.
Jasim