find all the strings matching ‘tony’ in an array of strings, then return how many there are. if there are none then return nil in ruby

main.rb
def count_tony_occurrences(arr)
  count = 0
  arr.each do |str|
    count += 1 if str.include?('tony')
  end
  count.zero? ? nil : count
end
141 chars
8 lines

In this code snippet, we defined a method count_tony_occurrences that takes an array of strings (arr) as an argument. We initialize a variable count to zero, which we increment if a string in the array includes the substring 'tony'. If count is 0, we return nil; otherwise, we return count.

We use the #each method to iterate over each string in the array, and the #include? method to check if the current string contains the substring 'tony'. If it does, we increment count. Finally, we use a ternary operator to check if count equals 0 – if it does, we return nil; otherwise, we return count.

gistlibby LogSnag