Linux Know-How provides a collection of introductory texts on often needed Linux skills.


ruby

ruby

A purely object-oriented scripting language. This language is a relative newcomer, but it is rapidly gaining popularity, and may well be the flavour of the future of programming.

To write a simple program in ruby, I open my favorite text editor and start a program with the following first line:

#!/usr/bin/ruby

Here is an example of a program that I wrote to help me understand the basics of the ruby language:

#!/usr/bin/ruby

#This is a comment

a = Array.new

print "Please enter a few words (type EXIT to stop):\n"

i = 0

while enterWord = STDIN.gets

enterWord.chop!

if enterWord == "EXIT"

break

end

a[i] = enterWord

i += 1

end

#sort the array

for i in 0...a.length-1 do

for j in i+1...a.length do

if a[j] < a[i]

tmp = a[i]

a[i] = a[j]

a[j] = tmp

end

end

end

#Output the results

print "You entered " + a.length.to_s + " entries.\n\n"

for i in 0...a.length do

print "Entry " + (i+1).to_s + ": "+ a[i] + "\n"

end

I save my ruby script to file "myprogram". To execute it, I need to type on the command line:

./myprogram


Last Update: 2010-12-16