今までのRubyバージョン

を、書いてみた。あたりまえだけどすげー楽。

1-08 cnt_spc.rb

text = ARGF.read
spc, tab, nl = text.count(" "), text.count("\t"), text.count("\n")
print "#{spc} #{tab} #{nl}\n"

1-09 cmpc_spc.rb

print ARGF.read.gsub(/ +/, " ")

1-10 esc_spc.rb

tab = {
  "\t" => "\\t",
  "\b" => "\\b",
  "\\" => "\\\\"
}
print ARGF.read.gsub(/[\t\b\\]/){|m| tab[m] }

1-12 show_words.rb

puts ARGF.read.split(/[ \t\n]+/)

1-13 histgram.rb

count = Array.new(11, 0)
ARGF.read.split(/[ \t\n]+/).each do |word|
  count[word.length <= 10 ? word.length : 0] += 1
end


print "length : times\n"
count.each_with_index do |x, i|
  unless i.zero?
    printf("%6d : %s\n", i, ("*" * x))
  end
end
printf("%6s : %s\n", "over10", ("*" * count[0]))

1-14 char_hist.rb

count = Hash.new(0)
ARGF.read.each_byte do |c|
  count[c] += 1
end

freq = Array.new(21, 0)
?a.upto(?z) do |c|
  freq[count[c] <= 20 ? count[c] : 0] += 1
end
?A.upto(?Z) do |c|
  freq[count[c] <= 20 ? count[c] : 0] += 1
end

printf "frequency : nominateds\n"
freq.each_with_index do |x, i|
  unless i.zero?
    printf("%9d : %s\n", i, ("*" * x))
  end
end
printf("%9s : %s\n", "over20", ("*" * freq[0]))

1-17 over80.rb

ARGF.each do |line|
  print line if line.length > 80
end

1-18 rm_spc.rb

ARGF.each do |line|
  line.rstrip!
  line.empty? or puts line
end