kastner (owner)

Forks

Revisions

gist: 198716 Download_button fork
public
Public Clone URL: git://gist.github.com/198716.git
Embed All Files: show embed
week3-hw1.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env ruby -wKU
 
def replace(char)
  return "{space}" if char == " "
  return "\\n" if char =~ /\n/
  return char
end
 
file_contents = open($0).read
@chars = file_contents.each_char.inject(Hash.new(0)) do |hash, char|
  hash[replace(char)] += 1; hash
end
 
def stats(title = "")
  dashes = "-" * 70
  puts dashes
  puts title unless title.empty?
  puts yield @chars
  print dashes + "\n\n"
end
 
stats "Character count analysis of #{$0}" do |chars|
  chars.sort {|a,b| a[1] <=> b[1]}.map do |c, count|
    "The Character #{c} is used #{count} time" + (count == 1 ? "" : "s")
  end
end
 
stats {|chars| "There are #{chars.count} unique characters in the file #{$0}" }
 
stats do |chars|
  singles = chars.find_all {|c| c[1] == 1}
  ret = "The following #{singles.size} characters are used 1 time"
  ret + singles.map{|c| c[0]}.join("\n")
end
 
stats do |c|
  most = c.max {|a,b| a[1] <=> b[1]}
  "most is #{c.find_all {|c| c[1] == most[1]}.map {|m| m[0]}} with #{most[1]}"
end
 
stats "The size of #{$0} is #{file_contents.length}" do |chars|
  "Character count total is #{chars.inject(0) {|a, c| a += c[1]}}"
end