Prerequisites

Learn Previous Tutorial : Ruby Tutorial : Step By Step Learning Ruby Programming Language

As I wrote in my previous tutorial, it is easy to start with Ruby Programming. It uses simple and clean English like syntax, even there is no need of semicolon at the End of statements as long as you put each statement in next line. Similarly it is not as much typical to define and use Ruby Variables as in C/Java/C# and other programming languages.

Defining Ruby Variables

Ruby Variables are not similar to C/C++ variables, these are simple to use but difficult to understand. So we will just learn here How to use Ruby Variables? And later we will understand them in our future tutorials.
There is no need to declare ruby Variables, instead you should initialize them before use. What I mean is – there is no need to tell Ruby that the variable is of Int or float or string type, Ruby will take care of it. See below examples to understand what I said.

Open your text editor, write below code and save it as BuffercodeRbVar.rb

1. puts “Hello, how are you? “
2.  name="Buffercode"
3.  puts name
4.  name= "MyName"
5.  puts name
6.  name=3
7.  a=4
8.  puts a+name
9.  name="buffercode.in"
10. puts "My name is #{name}"
11. puts "#{name. capitalize}, it is #{Time.now}"

And it produces the following output

 Hello, how are you?
 Buffercode
 MyName
 7
 My name is buffercode.in
 Buffercode.in, it is  2015-08-12 03:37:45 +0530

How it works ?

I hope above code and output is simple and understandable if you are familiar to any programming language. Here you just initialize name variable as name=”Buffercode” and use puts to print its value. Don’t you think it is too simple? Eh!!

You even can see in the above code( 6,7, and 8th line) that same variable can hold a string and a integer value . It means Ruby Variables are flexible too. And the important thing is that its result is also the expected one.

In the 10th line of above code you can observe that we call Ruby Variable inside a String in #{ }. When Ruby constructs this string, it looks at the current value of name and substitutes it into the string. Arbitrarily complex expressions are allowed to use in #{ }. As we did in last line of our code.

Have something to add or stuck somewhere in this Ruby Tutorial?? Share it in comments .

Follow us on Facebook, Google Plus and Twitter to get updated with our ruby tutorial.

Previous