Monday, December 10

Ruby on Rails Learning through examples

What ruby is used for?
Let us recollect the statement:
Ruby is "an interpreted scripting language for quick and easy object-oriented programming".
Ruby is used for many kind of applications be it writing automation scripts and run on your local pc's, or developing automation tools, or Website, or Blogs, Web Application or web based products and the list goes on...

We here pick up basics of Ruby just enough to get going with Rails and start developing simple websites and web applications.
All the things that we had said about ruby in earlier post What is Ruby? will be discussed in coming posts.
Learning through Examples:

Before even going for installing the ruby in your desktop, let us experiment on ruby with small examples and work/execute them here online.

This is our play ground:
This is called interactive ruby shell and we find ">>" similar to command/shell prompt. Now let's start with famous example of printing out "Hello World!" statement.
  1. type puts "Hello World!" >> puts "Hello World!"
  2. then click "Enter" button
  3. Now you would find the expected returned
  • >> puts "Hello World!"
  • Hello World!
    => nil
So puts is the ruby way of printing the things to console/prompt. The first line means to print the string within the quotes(i.e. Hello World!). Your would also find "=> nil" displayed in the next line of the Hello World! statement, puts always returns nil, which is Ruby’s absolutely-positively-nothing value.

Going on to the next example:
  • Ruby has simple syntax.
  • Ruby is dynamically typed.
  • Ruby needs no variable declarations.
  • Ruby operators are also methods.
Now I want to do simple math. Based on the above points,
to add two integers just type : 4+2
to subtract two integers just type : 4-2
to multiply two integers just type : 4*2
to divide two integers just type : 4/2
You can check out with other types also. Need not be of same type, since ruby is dynamic language at the run time they would be evaluated.
for example you type 2.0+3 and see for yourself.

Coming on to the variable declaration, ruby does not require the variable declarations. Let us the see this point also:
you type
>> a=5
=>5
>>b=2.0
=>2.0
>>c=a+b
=>7.0
As you see we have not declared the variables a,b,c and what type they hold. All these variables are evaluated at the run time and treated accordingly.
Ruby treat the operators(+,-,*,/,%...) as just like methods, which is conceptually derived from Smalltalk.

Download the pdf version of Learning Through Examples.
The pdf includes:
  • Useful links
  • Duck typing explained with example.
  • Examples with appropriate comments and explanation.
  • Ruby resources links.

No comments: