Variables in Ruby

Variable:

Now we want to store our data and want to use that data again and again. We store our data in memory. This memory is assign to a variable.

  1. #we are defining a variable
  2. var = 'harish'
  3. puts var
  4. # we are modifying that value
  5. var = 'another value'
  6. puts var

Here 'var' is a variable which stores the value 'this is a variable' in memory. This types of variables are called local variables. There are four more types of variables: instance variables, class variables, global variables and constant variables. We are not going to read about every variable at this time because I am assuming my readers are new with programming. We will read them when we will have need of these variables. At this time we discuss about constants.

Constants:

As clear from name, these are such variables whose values are fixed. We can define them only once and after that we can not modify them. Why do we need these variables? Think about constants like PI and other constants in formulas.

  1. # Now we are defining a constant
  2. # First letter of constant is always capital
  3. PI = 3.14
  4. puts PI

Note that first letter of the constants are always capital. It is good practice to write all letters of a constant capital.

Printing variables in string:

We can print variables inside the string:

  1. var = 'this is a variable'
  2. VAR = 'this is a constant'
  3. puts "now we are printing: #{var}"
  4. puts "now we are printing: #{VAR}"

We will get output:

  1. now we are printing: this is a variable
  2. now we are printing: this is a constant

Reserved keywords in Ruby:

Just like every language ruby language has also some reserved keywords which we can not use for giving name to any variable or constant.

BEGIN do next then
END else nil true
alias elsif not undef
and end or unless
begin ensure redo until
break false rescue when
case for retry while
class if return while
def in self __FILE__
defined? module super __LINE__

[000webhost_bottom_banner]



About Harish Kumar

Harish is an interested person in the field of web development and blogging. He works for the need of young web developers in learning various languages, latest technologies and other essential tips and tricks. If you need some help or you have some suggestion then you email him at harish@findalltogether.com without any hesitation. You can also suggest/demand for articles of your own choice.

Related Articles

Ruby is a pure object oriented, general purpose,interpreted and server side scripting and programming language. Ruby ...
Introduction to Ruby
In this step by step free tutorials we will learn about printing, comments, puts, print, begin, end and EOF methods f...
Getting Started with Ruby
In this tutorial of free step by step free tutorials series we read about variables, constant, printing in staring an...
Variables in Ruby

Login or Sign up to leave comment.