Last active
August 29, 2015 14:16
-
-
Save Andsbf/0015cf530766198d1408 to your computer and use it in GitHub Desktop.
Character Counting Exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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