Ruby - Introduction Variables

Introduction

Consider the following code:

Demo

x = 10 
puts x

Result

Here you assign the numeric value of 10 to a variable called x.

Variable Name

You can name variables however you like, with only a few limitations.

Variable names

  • must be a single unit no spaces!
  • must start with either a letter or an underscore
  • must contain only letters, numbers, or underscores
  • are case sensitive.

The following table demonstrates variable names that are valid and invalid.

Variable Name Valid Or Invalid?
x Valid
y2 Valid
_x Valid
7x Invalid (starts with a digit)
this_is_a_test Valid
this is a test Invalid (not a single word)
this'is@a'test! Invalid (contains invalid characters: ', @, and !)
this-is-a-test Invalid (looks like subtraction)

Demo

x = 100 
y = 10 # from ww w  .  j  a  va 2 s  . c  om
puts x - y 

x = 50 
y = x * 100 
x += y 
puts x

Result

Related Topics