-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 
2

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, only the number of frequency occurrences. Thank you for the answer!
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}"}

3 Comments

Awesome! Thank you! What if i did not necesarily know that the word "cat" exists. How would i output the number of the most frequencies?
Why did you select this as an answer if it doesn't meet the true requirements?
Strictly speaking, te answer did meet his requirements. With his commment he expanded the requirement :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.