Intro to Ruby - Variables and Scopes

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
Article Series - Intro to Ruby
- Intro to Ruby - Getting Started
- Intro to Ruby - Strings
- Intro to Ruby - Numbers
- Intro to Ruby - Ranges
- Intro to Ruby - Arrays
- Intro to Ruby - Hashes
- Intro to Ruby - Variables and Scopes
- Intro to Ruby - Methods
- Intro to Ruby - Blocks
- Intro to Ruby - Classes
- Intro to Ruby - Modules
- Intro to Ruby - Conditionals
- Intro to Ruby - Loops
- Intro to Ruby - Exceptions
- Intro to Ruby - Testing
- Intro to Ruby - Next Steps
No comments yet.
Leave a comment
You must be logged in to post a comment.
Search
Categories
- Adventures
(112)
- Announcements
(36)
- Business
(19)
- Electronics
(21)
- Epicurean
(10)
- Games
(3)
- Literature
(1)
- Mechanical
(4)
- Meetups
(18)
- Movies
(2)
- Music
(26)
- Photography
(1)
- Services
(27)
- Software
(132)