pyfl88 pyfl88 - 1 year ago 74
Ruby Question

Array find the number of same element

For example I have an array such as this:

["a","a","a","a","b","c","d","a","a","a"] #Expected result = 4

How can I find the number of same element, in my case
, before it change to different value?

Thanks in advance.

Answer Source
def nbr_consecutive(arr, str)
  start_ndx = arr.index(str)
  return 0 if start_ndx.nil?
  a = arr[start_ndx..-1]      
  a.index { |s| s != str } || a.size

arr = %w| e e a a a a b c d a a a |
  #=> ["e", "e", "a", "a", "a", "a", "b", "c", "d", "a", "a", "a"]

nbr_consecutive(arr, "e")
  #=> 2
nbr_consecutive(arr, "a")
  #=> 4
nbr_consecutive(arr, "b")
  #=> 1
nbr_consecutive(arr, "z")
  #=> 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download