Skip to content

Instantly share code, notes, and snippets.

@Andsbf
Last active August 29, 2015 14:16
Show Gist options
  • Save Andsbf/0015cf530766198d1408 to your computer and use it in GitHub Desktop.
Save Andsbf/0015cf530766198d1408 to your computer and use it in GitHub Desktop.
Character Counting Exercise
require 'pry'
def count_letters (string="")
counts = Hash.new(0)
string.split("").each do |element|
# binding.pry
counts[element] += 1 if element != " "
end
counts
end
puts count_letters('AAA BB C DDDD aaa bb c dddd f')
# require 'pry'
def count_letters (string="")
return "Invalid input" unless string.is_a? String
counts = Hash.new
string.split("").each_with_index do |element, index|
# binding.pry
counts[element.to_sym] ? (counts[element.to_sym] << index.to_s << " " unless element == " ") : (counts[element.to_sym] = index.to_s + " " unless element == " ")
end
counts
end
puts count_letters
puts count_letters('AAA BB C DDDD aaa bb c dddd f A BAtaksjdakjs ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment