Hello World (Ruby)
From LiteratePrograms
- Other implementations: Ada | ALGOL 68 | Alice ML | Amiga E | Applescript | AspectJ | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | Clojure | C++ | C# | Delphi | Dylan | E | Eiffel | Erlang | Forth | FORTRAN | Fortress | Go | Groovy | Haskell | Hume | IBM PC bootstrap | Inform 7 | Java | Java, Swing | JavaScript | LaTeX | Lisp | Logo | Lua | Maple | MATLAB | Mercury | OCaml/F Sharp | occam | Oz | Pascal | Perl | PHP | Pic | PIR | PLI | PostScript | Prolog | Python | Rexx | Ruby | Scala | Scheme | Seed7 | sh | Smalltalk | SQL | Standard ML | SVG | Tcl | Tcl Tk | Visual Basic | Visual Basic .NET | XSL
This is a simple Ruby program that prints a string to the console, then prints the integers 1 through 10 using a simple for loop.
<<hello_world.rb>>= print greeting print first ten integers
Printing a greeting is as simple as
<<print greeting>>= puts "Hello World!"
Ruby has a for-loop so print first ten integers can be implemented (using a range) like this:
for i in 1..10 puts i end
But the use of an iterator and a closure is more idiomatic:
<<print first ten integers>>= (1..10).each { |i| puts i }
Ruby is a scripting language so there is no compiler. To run the program you simply fire up the ruby interpreter and pass it the script:
$ ruby hello_world.rb Hello World! 1 2 3 4 5 6 7 8 9 10
Ruby is also an object-oriented language which contains classes. The hello world program as a class would be
<<hello_world_class.rb>>= class HelloWorld def greet() print greeting end def printFirstTenIntegers() print first ten integers end end
The class can be loaded, instantiated and executed inside the interpreter like this:
$ irb irb(main):001:0> require 'hello_world_class.rb' => true irb(main):002:0> hw = HelloWorld.new => #<HelloWorld:0x3ebe08> irb(main):003:0> hw.greet Hello World! => nil irb(main):004:0> hw.printFirstTenIntegers 1 2 3 4 5 6 7 8 9 10 => 1..10 irb(main):005:0>
or in a script, like this:
require 'hello_world_class.rb' hw = HelloWorld.new hw.greet hw.printFirstTenIntegers
References
- First Edition of Programming Ruby (Online) by Dave Thomas and Andy Hunt (The Pragmatic Programmers).
- Wikipedia entry on the Ruby programming language
Download code |