Skip to content

Instantly share code, notes, and snippets.

@FaisalFehad
Last active November 8, 2016 21:21
Show Gist options
  • Save FaisalFehad/7faf387e2fd194f019238a0f5f0bb0d2 to your computer and use it in GitHub Desktop.
Save FaisalFehad/7faf387e2fd194f019238a0f5f0bb0d2 to your computer and use it in GitHub Desktop.
A exercise to overwrite ruby count helper method
def letter_count(words, letter)
if words.include?(letter)
count = words.count(letter)
puts "The letter #{letter} appears #{count} time(s)"
else
puts "The letter #{letter} did not appear in '#{words}'"
end
end
# test
letter_count("Should I kill myself, or have a cup of coffee?", "E")
letter_count("Should I kill myself, or have a cup of coffee?", "e")
letter_count("Should I kill myself, or have a cup of coffee?", "x")
letter_count("Should I kill myself, or have a cup of coffee?", "X")
## returns
# The letter E did not appear in 'Should I kill myself, or have a cup of coffee?'
# The letter e appears 4 time(s)
# The letter x did not appear in 'Should I kill myself, or have a cup of coffee?'
# The letter X did not appear in 'Should I kill myself, or have a cup of coffee?'
# another solution which also works for and down case letters
def letter_count(words, letter)
letter = letter.downcase
times = words.to_s.count(letter)
if times == 0
puts "The letter #{letter} did not appear in '#{words}'"
else
puts "The letter #{letter} did appear #{times} times(s) in #{words}"
end
end
# test
letter_count("Should I kill myself, or have a cup of coffee?", "E")
letter_count("Should I kill myself, or have a cup of coffee?", "e")
letter_count("Should I kill myself, or have a cup of coffee?", "x")
letter_count("Should I kill myself, or have a cup of coffee?", "X")
## returns
# The letter e did appear 4 times(s) in Should I kill myself, or have a cup of coffee?
# The letter e did appear 4 times(s) in Should I kill myself, or have a cup of coffee?
# The letter x did not appear in 'Should I kill myself, or have a cup of coffee?'
# The letter x did not appear in 'Should I kill myself, or have a cup of coffee?'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment