Ruby - Introduction Variables


Consider the following code:


x = 10 
puts x


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)


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

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


Related Topics