Ruby For Beginners

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan. This article will cover its basic syntax and some basic programs. This article is divided into various sections for various topics.
1.SetUp : Let’s start by doing setup of the Ruby programming language.

For Linux Users, Go to terminal and type:

 apt-get install ruby

Windows users, click here and install ruby on your windows.

And the Ruby will be installed to your system.

In order to compile the a ruby program, Open your text editor and save the program with ‘.rb’ extension. After this, go to terminal(or command prompt) and type : ruby ‘file.rb’ where file is the name of the program you just made, and hence the program will be compiled.

2. A good first program
puts is used to print something on the console in Ruby.For eg. A string

puts "Hello World"
puts "Hello Again"

3. Comments

  • # is called the pound character in ruby and it is used to add comments to your code.
  • =begin, =end are used for multi-line comments

Example:

# this is a comment and wont be executed
= begin
this is 
a multi line
comment in ruby
= end

4. Maths: Simple mathematical functions can be carried out within the puts statements.Just as we use ‘%d’ or ‘%f’ and ‘&’ in C,we will use ‘#{ } in Ruby to get our work done.

puts "Alok has #{25+30/6} Rupees in his pocket"

Output : Alok has 30 Rupees in his pocket
The use of #{ } is how you insert Ruby computations into text strings.

5. Variables and Names : Variables in ruby are the same as that of any other dynamic programming language. You just don’t need to mention its type and ruby will know its type automatically.
Example:

cars = 100
drivers = 30
puts "There are #{cars} cars and #{drivers} drivers."

Output: There are 100 cars and 30 drivers.

6. Getting input

  • ‘gets.chomp’ is used to take input from user.
  • ‘print’ can be used instead for ‘puts’to print without a new line.

Example:

print "How old are you ? "
age = gets.chomp
print "How tall are you ?"
height = gets.chomp
puts " You are #{age} year old and your height is #{height} cms"

Run this code on your system as output will be given by the user

7. Prompting people for numbers

  • gets.chomp.to_i is used to get integer input from user.
  • gets.chomp.to_f is used to get float(decimal) input from user.

Example:

print "Give a number"
number = gets.chomp.to_i
puts "You just entered #{number}"

These are the most basic topics of Ruby that are essential for the beginner of Ruby programming language.We will cover more topics of Ruby in our upcoming articles.