Intro to Ruby - Variables and Scopes

Ruby

Overview

The following demonstrates some variable basics in Ruby. Even though the examples below only use local variables here are a few things to know about variable scopes:

  • All variables are case sensitive
  • Global variables = begin with $
  • Local variables = lowercase
  • Constant variables = uppercase
  • Instance variables = begin with @
  • Class variables = begin with @@

More examples of how these variables are used will be in future posts.

Code

# The following demonstrates a simple representation of variables as references to objects.
puts "01 Variables are References\n\n"
v1 = "Ruby"
v2 = v1
puts "v1 = " + v1
puts "v2 = " + v2
v2.chop!
puts "v1 = " + v1
puts "v2 = " + v2

# The following shows mass assignment of multiple variables to a single object.
# NOTE: Assignment is done right-to-left with the 'y' variable starting the sequence.
puts "\n02 Right-to-Left Assignment\n\n"
r = u = b = y = "ruby"
puts "r = " + r
puts "u = " + u
puts "b = " + b
puts "y = " + y

# Another example of variable assignment but this time multiple objects are assigned to multiple variables.
puts "\n03 Parallel Assignment\n\n"
one, two = 1, 2
puts "one = " + one.to_s
puts "two = " + two.to_s

# A simple example of additive assignment.
puts "\n04 Additive Assigment\n\n"
x = 5
x += 1
puts x

# A simple example of subtractive assignment.
puts "\n05 Subtractive Assigment\n\n"
x = 5
x -= 1
puts x

Output

01 Variables are References

v1 = Ruby
v2 = Ruby
v1 = Rub
v2 = Rub

02 Right-to-Left Assignment

r = ruby
u = ruby
b = ruby
y = ruby

03 Parallel Assignment

one = 1
two = 2

04 Additive Assigment

6

05 Subtractive Assigment

4

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 06-variables.rb.

What’s Next

Methods

Tags:

Wednesday, February 25th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.