Skip to content

Instantly share code, notes, and snippets.

@garrettgsb
Created April 27, 2016 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garrettgsb/eb8eb5dec6c99c2a87207328e69b32d3 to your computer and use it in GitHub Desktop.
Save garrettgsb/eb8eb5dec6c99c2a87207328e69b32d3 to your computer and use it in GitHub Desktop.
Counting Characters
require 'pry'
## Counts characters, omitting spaces
def char_count(target)
target = target.gsub(" ","")
tally = Hash.new(0)
target.each_char {|x| tally[x] += 1}
tally
end
puts char_count('Chi putao bu tu putao pi')
def char_positions(target)
# Assuming the index INCLUDING WHITE SPACE is important
tally = Hash.new{|h,k| h[k] = []} # What's going on here: http://stackoverflow.com/questions/2698460/strange-behavior-when-using-hash-default-value-e-g-hash-new
target.each_char.each_with_index {|x,i| tally[x] << i}
return tally
end
puts char_positions("Chi putao bu tu putao pi")
puts char_positions(".aaaaaaaabbbbbbbbccccccccdddddddd")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment