convert between characters and values
?a # => 97 ?\n # => 10
// string to integer: use []
'a'[0] # => 97 'hallo'[1] # => 97
// integer / number to character: use .chr
97.chr # => "a" 10.chr # => "\n"
//more info: "Ruby Cookbook", O'Reilly
DZone Snippets > ovhaag > character
11381 users tagging and storing useful source code snippets
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Oliver Haag www.ohcon.de
?a # => 97 ?\n # => 10
'a'[0] # => 97 'hallo'[1] # => 97
97.chr # => "a" 10.chr # => "\n"
class Counter def initialize() @characters = Hash.new(0) end def read() @text = IO.read("text.txt") end def count_chars @text.each_byte do |ch| @characters[ch] +=1 end end def report @characters.each do |key, value| puts "#{key.chr} (#{key}) occurs #{value} times" end end end
count = Counter.new() count.read count.count_chars count.report