HARSHAL Patil HARSHAL Patil

Naming variables -

is known as one of the most difficult tasks in computer programming. When you are naming variables, think hard about the names. Try your best to make sure that the name you assign your variable is accurately descriptive and understandable to another reader. Sometimes that other reader is yourself when you revisit a program that you wrote months or even years earlier.

When you assign a variable, you use the =symbol. The name of the variable goes on the left and the value you want to store in the variable goes on the right.

irb :001 > first_name = 'Joe'
=> "Joe"

Here we've assigned the value 'Joe', which is a string, to the variable first_name. Now if we want to reference that variable, we can.

irb :002 > first_name
=> "Joe"

As you can see, we've now stored the string 'Joe' in memory for use throughout the program.

Note: Make sure you don't confuse the assignment operator (=) with the equality operator (==). The individual = symbol assigns value while the == symbol checks if two things are equal.

Let's try a little something. Look at the following irb session.

irb :001 > a = 4
=> 4
irb :002 > b = a
=> 4
irb :003 > a = 7
=> 7

What is the value of b at this point? Take your best guess and then type this session into irb to find out.

You'll notice that the value of b remains 4, while a was re-assigned to 7. This shows that variables point to values in memory, and are not deeply linked to each other. If this is confusing, don't worry, we'll have plenty of exercises for you to complete that will make this information clear and obvious. And when in doubt, always try it out in irb.

Getting Data from a User

Up until now, you've only been able to assign data to variables from within the program. However, in the wild, you'll want other people to be able to interact with your programs in interesting ways. In order to do that, we have to allow the user to store information in variables as well. Then, we can decide what we'd like to do with that data.

One way to get information from the user is to call the gets method. gets stands for "get string", and is a lot of fun. When you use it, the program waits for the user to 1) type in information and 2) press the enter key. Let's try it out. Type these examples in irb to get the feel and play around with them for a bit if you'd like to.

irb :001 > name = gets
Bob
=> "Bob\n"

After the code, name = gets, the computer waited for us to type in some information. We typed "Bob" and then pressed enter and the program returned "Bob\n". The \n at the end is the "newline" character and represents the enter key. But we don't want that as part of our string. We'll use chomp chained to getsto get rid of that - you can put .chomp after any string to remove the carriage return characters at the end.

irb :001 > name = gets.chomp
Bob
=> "Bob"

There we go! That's much prettier. Now we can use the name variable as we so please.

irb :001 > name = gets.chomp
Bob
=> "Bob"
irb :002 > name + ' is super great!'
=> "Bob is super great!"

Variable Scope

A variable's scope determines where in a program a variable is available for use. A variable's scope is defined by where the variable is initialized or created. In Ruby, variable scope is defined by a block. A block is a piece of code following a method invocation, usually delimited by either curly braces {} or do/end. Be aware that not all do/end pairs imply a block*.

Now that you have an idea of what constitutes a variable's scope, one rule that we want you to remember is this:

Inner scope can access variables initialized in an outer scope, but not vice versa.

Looking at some code will make this clearer. Let's say we have a file called scope.rb.

# scope.rb

a = 5             # variable is initialized in the outer scope

3.times do |n|    # method invocation with a block
  a = 3           # is a accessible here, in an inner scope?
end

puts a

What is the value of a when it is printed to the screen? Try it out.

The value of a is 3. This is because a is available to the inner scope created by 3.times do ... end, which allowed the code to re-assign the value of a. In fact, it re-assigned it three times to 3. Let's try something else. We'll modify the same piece of code.

# scope.rb

a = 5

3.times do |n|    # method invocation with a block
  a = 3
  b = 5           # b is initialized in the inner scope
end

puts a
puts b            # is b accessible here, in the outer scope?

What result did you get when running that program? You should have gotten an error to the tune of:

scope.rb:11:in `<main>': undefined local variable or method `b' for main:Object
(NameError)

This is because the variable b is not available outside of the method invocation with a block where it is initialized. When we call puts b it is not available within that outer scope.

* Note: the key distinguishing factor for deciding whether code delimited by {} or do/end is considered a block (and thereby creates a new scope for variables), is seeing if the {} or do/end immediately follows a method invocation. For example:

arr = [1, 2, 3]

for i in arr do
  a = 5      # a is initialized here
end

puts a       # is it accessible here?

The answer is yes. The reason is because the for...do/end code did not create a new inner scope, since for is part of Ruby language and not a method invocation. When we use eachtimes and other method invocations, followed by {} or do/end, that's when a new block is created.

Types of Variables

Before we move on, you should be aware that there are five types of variables. Constants, global variables, class variables, instance variables, and local variables. While you should not worry too much about these topics in depth yet, here is a brief description of each.

HARSHAL Patil

HARSHAL Patil Creator

(No description available)

Suggested Creators

HARSHAL Patil