返回顶部

收藏

统计字母出现的次数

更多

[Ruby]代码

#Counts the number of times a 'letter' appears in a 'phrase'
def CountLetterOccurrence(letter, phrase, matchCase)
  # Gets the length of the phrase
  index = phrase.length
  # Splits the string into an array getting all of the characters from the phrase
  array = phrase.split(//)
  # Placeholder for how many letters that we find a match to
  count = 0
  # Loop through the array
  array.each do |character|
    # If we care about the letter CAsINg
    if matchCase == true
      # If the current character is the letter we are trying to find
      if character == letter
        # Add 1 to the count
        count = count + 1
        # Exit the if statement
      end
    # If we do not care about the word CAsINg
    else
      # If the current character is the letter we are trying to find
      if character.downcase == letter.downcase
        # Add 1 to the count
        count = count + 1
        # Exit the if statement
      end
      # Exit the if statement
    end
    # Exit the loop
  end
  # Return the number of letters matched
  return count
  # Exit the method
end

标签:ruby/rails

收藏

0人收藏

支持

0

反对

0