Introduction to Ruby and some playing around with the Interactive Ruby Shell (irb)

Ruby is the creation of a Japanese Computer Scientist Yukihiro Matsumoto. Ruby is an open-source, interpreted programming language. It has a very elegant syntax and you can even write code which might (somewhat) resemble functional style programming code. The Ruby interpreter can be installed on Windows, Linux or OS X. RVM ( Ruby Versioning Manager) is a good way to organize, install and maintain multiple ruby versions on the same machine. How to install Ruby and download ruby are good resources to setup Ruby and get it running.

Interactive Ruby Shell (irb)

This allows you to enter ruby commands line by line and see the output immediately. That's a pretty effective way to get used to the Ruby syntax, commands and keywords quickly. Open up an OS X Terminal or a Linux Shell and type in irb. On Windows, I believe this is fxri. You now find yourself in the Interactive Ruby Shell.

1. Type in "XYZ"

irb(main):005:0> "XYZ"

=> "XYZ"

The output you see => "XYZ" is the value being returned by the line or expression, after evaluation by the Ruby interpreter.

2. Type in puts "XYZ"

irb(main):007:0> puts "XYZ"

XYZ

=> nil

It displays "XYZ". The statement returns nothing, which is why you see the =>nil.

3. Simple Arithmetic expression

irb(main):008:0> 5 * 10 + 12 + 9 - 20

=> 51

4. Two consecutive asterisks indicate "raise to the power of". So, 5**2 = 5^2 = 25.

irb(main):013:0> 5**2

=> 25

5. Let's take a quick tour of 'Math' which is a built in module, which provides you methods and constants which are very useful while making mathematical calculations. 'sqrt' for instance is the way to find the square root of a given number.

irb(main):014:0> Math.sqrt(10 + 20)

=> 5.477225575051661

6. Here's how we find the sine of an angle. Math::PI is the value of the constant PI as provided by the Math module. Sine of PI/2 radians, or 90 degrees = 1.

irb(main):023:0> Math.sin(Math::PI/2)

=> 1.0

7. Inverse trigonometric ratios. Lets find the sine-inverse or the arcsine of 1 and 0.5

irb(main):024:0> Math.asin(1)

=> 1.5707963267948966

irb(main):025:0> Math.asin(0.5)

=> 0.5235987755982989

The values you see are in radians; in terms of degrees they are 90 and 30 degrees respectively.