November 2001
Intermediate to advanced
218 pages
6h 22m
English
Like Python or Perl, Ruby is a scripting language. Scripting languages offer some great advantages over other languages, such as C++ and Java. They allow programmers to show off a lot of programming concepts and principles in a relatively small amount of space. Ruby does this, while maintaining code readability.
# the "Hello World."
print "Hello World.\n"
# output file contents in reverse order
print File::readlines(path).reverse
# print lines that contains the word "Ruby".
while line = gets( )
if /Ruby/ =~ line
print line
end
end
# class and methods
class Animal
def legs
puts 4
end
end
class Dog<Animal
def bark
puts "bow!"
end
end
fred = Dog::new
fred.legs # prints 4
fred.bark # prints bow!
# exception handling
begin
printf "size of %s is %d\n", path, File::size(path)
rescue
printf "error! probably %s does not exist\n", path
end
# rename all files to lowercase names
ARGV.each {|path| File::rename(path, path.downcase)}
# network access
require 'socket'
print TCPSocket::open("localhost", "daytime").read
# Ruby/Tk
require 'tk'
TkButton.new(nil, 'text'=>'hello', 'command'=>'exit').pack
Tk.mainloopRead now
Unlock full access