February 21, 2019
Hot Topics:

Should Ruby Be Added to Your Programming Repertoire?

  • April 8, 2005
  • By W. Jason Gilmore
  • Send Email »
  • More Articles »

Script Execution

Executing a Ruby script is as easy as placing a few commands in a text file and executing the file with the ruby interpreter:

%>ruby [program file]

For example, place the following commands in a file, saving it as datefun.rb:

# What's your birthday?

bday = DateTime.new(1975, 07, 04)

# What's today's date?

today = DateTime.now

# Difference in days between today and your birthday

daysold = today - bday

# Output difference

puts "You are #{daysold.to_i} days old."

# Were you born on a leap year?

puts "Were you born on a leap year? #{Date.leap?(bday.year)}."

# Next birthday falls on what day?

presentbday = Time.local(today.year, bday.month, bday.day)

puts "This year's birthday falls on a #{presentbday.strftime('%A')}."

Let's execute this program and review the output:

C:\ruby\tests>ruby datefun.rb
You are 10862 days old.
Were you born on a leap year? false.
This year's birthday falls on a Monday.

You can forego running scripts through the Ruby interpreter by adding the #! (pronounced shabang! Say it loud!) to the very first line of the script, followed by the path to your Ruby executable. For example:


Next, make your program executable by executing:

%>chmod +x datefun.rb

Now, you should be able to execute the datefun.rb script as you would a typical program:


I hope this brief tutorial gives you a taste of what Ruby is capable of adding to your repertoire! Stay tuned for future installments on this fascinating language.

Learning More

The Ruby language home page: http://www.ruby-lang.org/en/

Ruby Central, Inc. (non-profit organization dedicated to supporting the Ruby language): http://www.rubycentral.org/

Ruby Weekly News (a weekly summary of the ruby-talk mailing list discussions): http://rubyweeklynews.org/

The RubyGems package manager: http://rubyforge.org/projects/rubygems/

The RubyForge open source project repository: http://www.rubyforge.org/

The Ruby on Rails Web framework: http://www.rubyonrails.com/

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) spends his days (and many nights) running Apress' open source program. He's the author of the best-selling Beginning PHP 5 and MySQL: Novice to Professional (Apress, 2004. 748pp.). His writings on open source technologies have been featured within many of the computing industry's leading publications, including Linux Magazine, O'Reillynet, Devshed, Zend.com, and Webreview. Jason loves receiving e-mail, so don't hesitate to write him at wjATwjgilmore.com.

Page 2 of 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date