pyfl88 pyfl88 - 3 months ago 8
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
"a"
, before it change to different value?

Thanks in advance.

Answer
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
end

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
Comments