Friday, June 5, 2009

Ruby

Note: This post assume that you have successfully installed Ruby on Rails in your computer.

Ruby as a Calculator

Type following command on your command prompt

irb --simple-prompt

and press "Enter" key from the keyboard. You will received following respond

C:\>irb --simple-prompt

>>

At ">>" command prompt, enter "10+20" and press enter key. You will received following respond

C:\ruby>irb --simple-prompt

>> 10+20

=> 30

>>

A "=>" command prompt symbol showing answer of the "10+20" airthmetic equation. Again ">>" command prompt symbol come so you will use this prompt for new airthmetic equation. Ruby support addition (+), subtraction (-), multiplication (*) and division (/) airthmetic operator. Remaining airthmetic operator I will discuss some time later.

If you want to out of irb then type exit at ">>" command prompt and press "Enter" key from the keyboard.

>>exit

C:\ruby>

In my case I am using these command inside ruby folder at "C" drive, so "C:\>Ruby" prompt comes.

Number Datatypes in Ruby

Try following division arithmetic operator

C:\ruby>irb --simple-prompt
>> 3/2
=> 1
>>

An integer is a whole number, like 3, 6, -5, etc. When you operate using only integers, Ruby will give you an Integer answer. 3/2 is 1.5, but that isn't an integer, so Ruby gives you 1 instead.

But if you try 3.0/2.0 then ? let's try

C:\ruby>irb --simple-prompt

>> 3.0/2.0

=> 1.5

>>

A float is a decimal number, like 3.14, 6.51, 3.0, etc. When you operate using only float, Ruby will give you an float answer. 3.0/2.0 is 1.5

More Arithmetic Operator

Exponent (**)

C:\ruby>irb --simple-prompt
>> 6 ** 2
=> 36
>>

Remainder (%)

C:\ruby>irb --simple-prompt
>> 6 % 4
=> 2
>> 7.1 %2
=> 1.1
>>

Working with Large Number