Hello, Ruby!

Ruby was come preinstalled on Mac OS X Mountain Lion, so for you who want to develop application using Ruby this one will come in handy. To check the Ruby version installed on your Mac, fire up the Terminal, and type:

ruby -v

For other OSes please refer to this article in downloading and installing Ruby on Mac, Linux, and Windows.

Mine is ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin12.0], but your’s may be different. Current stable version is 1.9.7 and in currently development is 2.0 (Beta). If you just require to test drive programming in Ruby, then you don’t need the latest version of Ruby. The newer version of Ruby offer more bug fixes and more built-in library (Gem?) for more productivity.

This time I’ll demonstrate Ruby “Hello, Ruby!” programming on Mac OS X. A Ruby script file has .rb extension so create a hello.rb file and put the following line and save.

puts "Hello!"
def name
  return "My name is Ruby!"
def greet
  "Nice to meet you."
puts name
puts greet

Then run those ruby file from your terminal by executing the following command:

ruby hello.rb

you will find something similiar like this:

aryo@MacBookPro ~/$ ruby hello.rb 
My name is Ruby!
Nice to meet you.
aryo@MacBookPro ~/$

If you see in more detail to the second function, greet. Ruby requires no return keyword to return the value of the function. Ruby will automatically return the evaluation of the last line of the function. Thus giving more flexibility (or inconsistency?) in programming.

Ruby also has it’s interactive shell, named IRB (Interactive Ruby Shell). The shell can be launched by irb command from Terminal. Here is an example:

aryo@MacBookPro ~/$ irb
>> puts "Hello"
=> nil
>> def name
>> return "My Name is Ruby!"
>> end
=> nil
>> def greet
>> "Nice to meet you."
>> end
=> nil
>> name
=> "My Name is Ruby!"
>> greet
=> "Nice to meet you."

You can find more Help and Documentation in programming with Ruby here. Happy coding with  Ruby!