Natalia Natalia - 4 years ago 113
Ruby Question

How do I check if an element occurs more than twice in an array, subject to a string pattern?

I'm using Ruby 2.4. I know how to check if an eleemnt has never occurred more than twice in an array, using

data_arr.count(string) <= 2


but what if my array is

["1/5", "2/6", "3/5", "4/7", "3/8", "3/9"]


how do I check that the first number before the "/" never occurs more than twice when it is found before the "/"? That is, in the above example, "1" never occurs more than twice (only in the element "1/5") but "3" occurrs 3 times before the "/".

Answer Source

You might begin by using hash::new with a default value of zero to construct a counting hash.

arr = ["1/5", "2/6", "3/5", "4/7", "3/8", "3/9"]

h = arr.each_with_object(Hash.new(0)) { |s,h| h[s[/\d+(?=\/)/]] += 1 }
  #> {"1"=>1, "2"=>1, "3"=>3, "4"=>1} 

Then write

h.any? { |_,v| v > 2 }
  #=>  true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download