Skip to content

Instantly share code, notes, and snippets.

@ruxandrafed
Created September 2, 2015 20:07
Show Gist options
  • Select an option

  • Save ruxandrafed/587ff9ba1136cbe51b81 to your computer and use it in GitHub Desktop.

Select an option

Save ruxandrafed/587ff9ba1136cbe51b81 to your computer and use it in GitHub Desktop.
def count_letters(str)
letters = Hash.new{0}
str = str.gsub(/\s+/, "") #removes spaces
str.each_char { |c| letters[c] += 1 }
puts letters.inspect
end
puts "What's your string?"
user_input = gets.chomp
count_letters(user_input)
# Return indices of each character
def indices_letters(str)
letters = Hash.new(0)
str.each_char.each_with_index do |c, i|
if letters.has_key?(c)
letters[c].push(i)
else
letters[c] = Array.new(0)
letters[c].push(i)
end
end
# removing spaces at this stage so that we return correct indices
letters.delete(" ")
puts letters.inspect
end
indices_letters(user_input)
# More elegant
def indices_letters_elegant(str)
letters = Hash.new {|h,k| h[k] = [] } # we make sure we have an empty array at each key
str.each_char.each_with_index {|c, i| letters[c].push(i)}
letters.delete(" ")
puts letters.inspect
end
indices_letters_elegant(user_input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment