Monday, November 10, 2014

Ruby for Beginners : The Basics

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It's very simple and easy to learn. So, this is a tutorial for beginners in which I shall be covering the basics of Ruby and gradually more tutorials will be posted.

If you have not yet already installed the Ruby on your machine, you can refer the Installation steps in this article to download the setup and starting coding.

Interactive Ruby is the smartest way for the beginners to start learning Ruby. It can be opened from the Start Menu of your Windows under the Ruby section, after the installation is complete. In case of Mac OS and Linux, you can open up the Terminal(Mac) or shell(Linux) and type the command irb and hit enter. Something like the below should be displayed when you open it.
irb(main):001:0>
Now, when any value is entered whether a number or a string, Ruby returns some value. Any piece is called 'Object' in Ruby.
irb(main):001:0> "Hello World"
=> "Hello World"
irb(main):002:0> 7
=> 7
Interactive Ruby is a calculator on its own. Simple mathematical calculations can be performed very easily on irb terminal, that include basic arithmetic operations(Addition, Subtraction, Multiplication, Division), exponent and remainder. Division is done based on the input type: Integer or Float.
irb(main):003:0> 4+5
=> 9
irb(main):004:0> 6-3
=> 3
irb(main):005:0> 3*2
=> 6
irb(main):006:0> 5/3
=> 1
irb(main):007:0> 5.0/3.0
=> 1.6666666666666667
irb(main):008:0> 2**3
=> 8
irb(main):009:0> 7%4
=> 3
String operation is also very easy to perform in Ruby. There are many methods for strings manipulation.
irb(main):010:0> "Hello World".length
=> 11
irb(main):011:0> "Hello "+"World"
=> "Hello World"
irb(main):012:0> "Hello ".concat("World")
=> "Hello World"
irb(main):013:0> "hello".capitalize
=> "Hello"
irb(main):014:0> "hello".reverse
=> "olleh"
irb(main):015:0> "hello".next
=> "hellp"
irb(main):016:0> "hello".upcase
=> "HELLO"
irb(main):017:0> "HELLO".downcase
=> "hello"
irb(main):018:0> "hElLo".swapcase
=> "HeLlO"
Variable can be used in Ruby right away without declaration. You just need to set the value of a variable and start using it. Variable name must begin with lowercase letter. Constants are the variables with first letter in uppercase.
irb(main):019:0> city = "Delhi"
=> "Delhi"
irb(main):020:0> age = 25
=> 25
Print and Puts command are used to print the value in Ruby. The print command just prints the value to the screen whereas puts adds a new (blank) line after value to be printed. Here, nil is returned by the commands which is Ruby’s absolutely-positively-nothing value.
irb(main):021:0> print "Hello"
Hello=> nil
irb(main):022:0> puts "Hello"
Hello
=> nil
These basics can be practiced in Interactive Ruby with ease which will give you the basic idea of how Ruby commands works. In next article, I will cover the Control Flow in Ruby.

No comments:

Post a Comment