[ next ] [ prev ] [ contents ] [ up to Ruby Immersion ] Using Ruby

Word and Character Counting

#!/usr/bin/env ruby

chars = 0
words = 0
lines = 0

# Count the stuff 

while line = gets
  chars += line.size
  words += line.split.size
  lines += 1
end

# Display the results

puts "Chars=%s, Words=%s, Lines=%s" % [
  chars, words, lines
]

  • Comments begin with "#"
    • Notice standard script header line

  • Everything is an object
    • "a b".size => 3
    • "a b".split => ['a', 'b']
    • ["a", "b"].size => 2

  • No semi-colons needed. Lines continue automatically if needed, otherwise use a "\"

  • [a, b, c] is a three element array

Output

Chars=85, Words=17, Lines=5


[ next ] [ prev ] [ contents ] [ up to Ruby Immersion ] Copyright 2003 by Jim Weirich.
Some Rights Reserved