-1

I am new to ruby and this might be a simple solution but i can't seem to figure out how to output the number of the most frequency occurrence in the array. Assume that animals is an array of strings. Write a set of Ruby statements that reports to output how many times the word “cat” appears in the array. For example, if the array animals has the contents of [“cat”, “dog”, “cat”, “cat”, “cow”], your script should write out the number 3. Here is what i have so far, which gives me an output of cat but i want to just show how many times it repeats. Thanks!

array = [ "cat", "dog", "cat", "cat", "cow" ]
repeat_item = array.uniq.max_by{ |i| array.count( i ) }
puts repeat_item 
  • This is negligibly different from [this question](http://stackoverflow.com/questions/569694/count-duplicate-elements-in-ruby-array). You should have no problems outputting whatever this homework problem requires. – coreyward May 04 '17 at 20:13
  • I smell a homework question. "[How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/128421)" also "[How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/questions/261592)" – the Tin Man May 04 '17 at 21:22

2 Answers2

1

So by the wording of the question, we only care about the number of occurrences for the string cat:

array.count { |x| x == 'cat' }
=> 3
Derek Wright
  • 1,452
  • 9
  • 11
0
puts array.select{|e|e=='cat'}.count

After reading the comments I add another solution which should meet additional requirements:

array = [ "cat", "dog", "cat", "cat", "cow", "cow", "cow" ]

repeat_item = array.uniq.each_with_object({}){|x, result| result[x] = array.count(x) }

max_count = repeat_item.values.max
max_item = repeat_item.key(max_count)

puts "#{max_item}: #{max_count}"

I deliberately left the variables to illustrate the approach. Note that in case of some entries with the same occurrence it yields the first one

Another solution: one line but not that easy to understand

puts array.group_by{|i| i }
     .max_by{|i,v| v.count }
     .instance_eval{|i| "#{i.first}: #{i.last.count}"}
Bernhard
  • 686
  • 8
  • 20