Ruby Course

Introduction.

Variables are a way of assigning data to names in your programs. You can think of a variable as a box with a label on it: it stores something and has a name so that you know what’s inside. This is an imperfect metaphor as you’ll see by the end of this lesson, but it should help with understanding variables for now.

Lesson overview

This section contains a general overview of topics that you will learn in this lesson.

  • Describe what a variable is and how to assign it a value or expression.
  • Explain what the += , -= , *= , and /= assignment operators do.
  • Describe the naming conventions for variables.

Declaring a variable

This is how to create a variable in Ruby:

You can also assign the result of an expression to a variable.

Variable names are reusable, so you can assign a new value to a variable at any point in your program. Naturally, doing so will override the original value.

There will often be scenarios where you want to perform an operation on the original value of a variable and then reassign the result of that operation to the same variable.

Because this is a common scenario, Ruby provides a nice shorthand assignment operator for doing this: += .

There are similar assignment operators for all the common math operators :

How to name variables

Ruby is a language that aims to be natural to read and easy to write. Remember this when you’re naming your variables. The name should, as clearly as possible, describe what the value of the variable represents.

Naming variables clearly will pay dividends when you review your code months after you’ve written it, when you can no longer remember what that variable was designed to store. From now on, when naming your variables, remember the following quote by John Woods:

Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live.

The most basic thing you can do to write clean, maintainable code is to name your variables properly. So get into this habit early to avoid psychopath programmers coming after you.

Variable names should always be lowercase, and multiple words that make up a variable name should be split by an underscore. This is known as snake_case .

Variables are references

The information you name with a variable is stored in memory on your computer, so a variable is effectively a reference or a pointer to that address in memory. This is important to know as it can sometimes be the cause of unexpected behavior from your code.

Let’s look at an example of this unexpected behavior, with two variables: desired_location , which is assigned to the string “Barcelona”, and johns_location , which is assigned to the desired_location variable. Both variables are pointing to where “Barcelona” is stored in memory.

Unexpected behavior happens if the string “Barcelona” that is stored in memory is modified. One way to modify a string is to use the upcase! method, instead of the safe upcase method. If the string is modified using johns_location.upcase! then desired_location will also reflect that change:

This example may be hard to completely understand at this point in the lesson. The important concept is that assigning variables to other variables can have unintended side effects. Just because you can do it, doesn’t mean you should. You will have the opportunity to revisit this example in one of the following assignments.

  • Read the Variables chapter from LaunchSchool’s brilliant Introduction to Programming With Ruby . As indicated in this article, remember that you should not use $global_variables . Additionally, @@class_variables are rarely needed and easily misused.
  • Overview of Variables
  • Reusing Variable Names
  • Things on the Right Go First
  • Open up a Ruby replit.com or use IRB in your command line and try naming some variables and assigning values to them. Don’t worry so much about good naming conventions at this stage. Instead, experiment with different variable names and see what is valid. Try using symbols or numbers in your variable names. Try assigning a variable to another variable and observe the behavior when using upcase! , as in the example above. If you come across anything quirky, Google it to find out why it happened.

Knowledge check

This section contains questions for you to check your understanding of this lesson. If you’re having trouble answering the questions below on your own, review the material above to find the answer.

  • What is a variable?
  • How do you assign a value or an expression to a variable?
  • What does the += assignment operator do?
  • What does the -= assignment operator do?
  • What does the *= assignment operator do?
  • What does the /= assignment operator do?
  • What are the variable naming conventions?

Additional resources

This section contains helpful links to related content. It isn’t required, so consider it supplemental.

  • Read the full Variables chapter from The Bastards Book of Ruby if you can’t get enough about variables.
  • Variables as Pointers , from LaunchSchool’s Introduction to Programming With Ruby .
  • A visual guide to variables from the Variables chapter of The Bastards Book of Ruby
  • If you want to know more about Ruby’s naming conventions, check out the Ruby Style Guide . Don’t get too deep into it; just know that it’s there.

Support us!

The odin project is funded by the community. join us in empowering learners around the globe by supporting the odin project.

Ruby 2.7 Reference SAVE UKRAINE

In Ruby, assignment uses the = (equals sign) character. This example assigns the number five to the local variable v :

Assignment creates a local variable if the variable was not previously referenced.

Abbreviated Assignment

You can mix several of the operators and assignment. To add 1 to an object you can write:

This is equivalent to:

You can use the following operators this way: + , - , * , / , % , ** , & , | , ^ , << , >>

There are also ||= and &&= . The former makes an assignment if the value was nil or false while the latter makes an assignment if the value was not nil or false .

Here is an example:

Note that these two operators behave more like a || a = 0 than a = a || 0 .

Multiple Assignment

You can assign multiple values on the right-hand side to multiple variables:

In the following sections any place “variable” is used an assignment method, instance, class or global will also work:

You can use multiple assignment to swap two values in-place:

If you have more values on the right hand side of the assignment than variables on the left hand side, the extra values are ignored:

You can use * to gather extra values on the right-hand side of the assignment.

The * can appear anywhere on the left-hand side:

But you may only use one * in an assignment.

Array Decomposition

Like Array decomposition in method arguments you can decompose an Array during assignment using parenthesis:

You can decompose an Array as part of a larger multiple assignment:

Since each decomposition is considered its own multiple assignment you can use * to gather arguments in the decomposition:

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Ruby variables

last modified October 18, 2023

In this part of the Ruby tutorial, we examine variables in more detail.

A variable is a place to store data. Each variable is given a unique name. There are some naming conventions which apply to variable names. Variables hold objects. More precisely, they refer to a specific object located in computer memory. Each object is of certain data type. There are built-in data types and there are custom-built data types.

Ruby belongs to the family of dynamic languages. Unlike strongly typed languages like Java, C or Pascal, dynamic languages do not declare a variable to be of certain data type. Instead of that, the interpreter determines the data type at the moment of the assignment. Variables in Ruby can contain different values and different types of values over time.

The term variable comes from the fact that variables, unlike constants, can take different values over time. In the example, there is a variable called i . First it is assigned a value 5, later a different value 7.

Ruby variable naming conventions

Ruby, like any other programming language, has some naming conventions for variable identifiers.

Ruby is a case sensitive language. It means that age and Age are two different variable names. Most languages are case sensitive. BASIC is an exception; it is a case insensitive language. While we can create different names by changing the case of the characters, this practice is not recommended.

The code example defines two variables: I and i . They hold different values.

Variable names in Ruby can be created from alphanumeric characters and the underscore _ character. A variable cannot begin with a number. This makes it easier for the interpreter to distinguish a literal number from a variable. Variable names cannot begin with a capital letter. If an identifier begins with a capital letter, it is considered to be a constant in Ruby.

In this script, we show a few valid variable names.

Variable names should be meaningful . It is a good programming practice to choose descriptive names for variables. The programs are more readable then.

The script shows three descriptive variable names. The place_of_birth is more descriptive to a programmer than e.g. pob. It is generally considered OK to choose simple variable names in loops.

Ruby sigils

Variable identifiers can start with special characters also called sigils . A sigil is a symbol attached to an identifier. Variable sigils in Ruby denote variable scope. This is in contrast to Perl, where sigils denote data type. The Ruby variable sigils are $ and @ .

We have four variables with different scopes. A scope is the range in which a variable can be referenced. We use special built-in methods to determine the scope of the variables.

A variable without a sigil is a local variable. A local variable is valid only locally: e.g., inside a method, block or a module.

Global variables start with $ character. They are valid everywhere. The use of global variables should be limited in programs.

A variable name starting with a @ sigil is an instance variable. This variable is valid inside an object.

Finally we have a class variable. This variable is valid for all instances of a specific class.

The local_variables gives an array of all local variables defined in a specific context. Our context is Ruby toplevel.

Similarly, the global_variables produces an array of globals. We do not print all globals to the terminal, because there are many of them. Each Ruby script starts with a bunch of predefined variables. Instead of that, we call the include? method of the array to check if our global is defined in the array. Also note that we are referencing variables with their symbols. (Symbols start with a colon character.)

The self pseudo variable points to the receiver of the instance_variables method. The receiver in our case is the main , the Ruby toplevel execution area.

Finally we have an array of class variables. The main is an instance of the Animal class.

We see symbolic names of the variables.

Ruby local variables

Local variables are variables that are valid within a local area of a Ruby source code. This area is also referred to as local scope . Local variables exist within the definition of a Ruby module, method, class.

We have a method called method1 , which has one variable. The variable is local. This means that it is valid only within the method definition. We can refer to the x variable only between the method name and the end keyword.

This is the definition of the method1 method. Inside the method, we create a local x variable. We print the value of the variable to the terminal.

The method is called.

We try to refer to a local variable outside the definition of the method. This leads to a NameError . The Ruby interpreter cannot find such identifier.

Running the example gives the above output.

The following example is a slight modification of a previous example.

We have two x variables. One is defined inside the method1 and the other one is defined outside. They are two distinct local variables. They do not clash with each other.

We have created a local x variable, which holds value 5. The variable is valid in the local scope of the main execution area. It is not valid inside the method1 .

Inside the definition of the method1 a new local variable x is defined. It has value 10. It exists in the body of the method1 method. After the end keyword it ceases to exist.

If a method takes parameters, a local variable is created for each of these parameters.

We have a method definition, which takes two values. The method returns the area of a rectangle.

The rectangle_area method takes two parameters. They are the sides of a rectangle, for which we calculate the area. Two local variables are automatically created for identifiers a and b. We call the local_variables method to see what local variables we have in the method.

Here we pass two values to the method rectangle_area . The values will be assigned to two local variables, created inside the method.

The output shows three things. The first two are the names of the local variables within the rectangle_area method. The third is the calculated area of the given rectangle.

A method may be defined inside another method. The inner methods have their own local variables.

In this Ruby script, we create three methods. The method2 and method3 are inner methods. The method2 is defined inside the method1 and the method3 is defined inside method2 . Each method's local variables are only accessible in the method in which they were defined.

From the output we can see that method1 has two local variables, m1 and m2 . The inner method2 has local variables m3 and m4 . The method3 , the innermost method, has local variables m5 and m6 .

The last example of this section will present several demonstrations of a local scope.

In the code example, we create local variables inside a module, method, class and toplevel. The local_variables is a method of the Kernel module that returns all current local variables.

A module is a collection of methods and constants. We create two local variables m1 and m2 .

Two local variables, v and w , are created in method1 .

The x and y local variables are created inside the definition of the Some class.

Finally, two local variables that belong to the Ruby toplevel's local scope are created.

The output shows local variables for each local scope.

Ruby global variables

Global variables are valid everywhere in the script. They start with a $ sigil in Ruby.

The use of global variables is discouraged. Global variables easily lead to many programming errors. Global variables should be used only when there is a reason to do so. Instead of global variables, programmers are advised to use local variables whenever possible.

In the example we have a global variable $gb . We show that the variable can be referenced in a module, method, class and a toplevel. The global variable $gb is valid in all these entities.

A global variable $gb is created; it has value 6.

Inside a module's definition we print the global variable's value.

Inside the definition of a method we print the value of the global variable.

Inside the definition of a class we print the value of the global variable.

Finally, in the toplevel execution area we print the global variable's value and whether the variable is in the array produced by the global_variables method.

The output of the example confirms that the global variable is accessible everywhere.

When a Ruby script starts, it has access to multiple predefined global variables. These globals are not considered harmful and help solve common programming jobs.

The script shows a $LOAD_PATH global variable. The variable lists directories which are searched by load and require methods. The $: is a short synonym for the $LOAD_PATH name.

More global variables will be presented in the Predefined variables section of this chapter.

Ruby instance, class variables

In this section we briefly cover instance and class variables. They will be described in Object-oriented programming chapter in more detail.

Instance variables are variables that belong to a particular object instance. Each object has its own object variables. Instance variables start with a @ sigil. Class variables belong to a specific class. All objects created from a particular class share class variables. Class variables start with @@ characters.

We create a custom Being class. The Being class has one class and one instance variable.

The @@is is an class variable. This variable is shared by all instances of the Being class. The logic of this example is that Being is and NotBeing is not.

The initialize method is a constructor. The method is called when the object is created. A @name instance variable is created. This variable is specific to a concrete object.

The to_s method is called, when the object is a parameter of a printing method, like p or puts . In our case, the method gives a short human readable description of the object.

The does_exist? method returns the class variable.

Three objects from the Being class are created. Each of the objects has a different name. The name of the object will be stored in the instance method, which is unique to each object instance. This will be used in the to_s method, which give a short description of the object.

The puts method takes the created objects as three parameters. It calls the to_s method on each of these objects.

Finally, we call the does_exist? method of each of the instances and print their return values. The output of these three methods is the same, because each method returns the class variable.

Output of the example. The first three messages are unique. The strings are stored in the instance variables of the objects. The true value is the value of the class variable, which is called three times.

Ruby environment & command-line variables

The ENV constant gives access to environment variables. It is a Ruby hash. Each environment variable is a key to the ENV hash.

The ARGV constant holds command-line argument values. They are passed by the programmer when the script is launched. The ARGV is an array that stores the arguments as strings. The $* is an alias to the ARGV .

Both ENV and ARGV are global constants.

In the script we loop through the ARGV array and print each of its values.

We have given three command-line arguments. They are printed to the console, each on a separate line.

The following example will deal with environment variables.

The script will print values of three environment variables to the terminal. The values depend on the OS settings of our operating system.

This is a sample output.

Ruby pseudo variables

Ruby has a few variables which are called pseudo variables . They are different from regular variables. We cannot assign values to pseudo variables.

The self is the receiver of the current method. The nil is the sole instance of the NilClass . It represents the absense of a value. The true is the sole instance of the TrueClass . It represents boolean true. The false is a sole instance of FalseClass . It represents boolean false.

The true and false are values of a boolean datatype. From another point of view, they are instances of specific classes. This is because everything in Ruby is an object. This looks like unnecessarily complicated. But it is the consequence of the aforementioned Ruby idiom.

This is an example of pseudo variables. We print all four pseudo variables with the p method. Then we find out the class name for all of them.

In this context, the self pseudo variable returns the main execution context.

Example output.

In the second example of this section, we further look at the self .

As we have said, the self references the receiver of the current method. The above example shows three examples of different receivers.

The receiver is the class called Some .

Here is another receiver: a class named Other .

And the third receiver is the Ruby toplevel.

The last example of the section will present other three pseudo variables.

The above example shows true , false and nil pseudo variables at work.

The true is used in boolean expression. The message is always printed.

This message is never printed. The condition is not met. In the boolean expression we always get a negative value.

If global values are referenced and have not been initialized, they contain the nil pseudo variable. It stands for the absence of a value.

Ruby predefined variables

Ruby has plenty of predefined global variables. This is a heritage of Perl language. Ruby was influenced strongly by Perl. They are accessible when the Ruby script starts. We have a few examples for the predefined Ruby variables.

Three predefined variables have been used: $0 , $* and $$ . The $0 stores the current script name. The $* variable stores command-line arguments. And the $$ stores the PID (process id) of the script.

The $? global variable stores the exit status of the last executed child process.

We run two external child processes and check their exit status with the $? variable.

With the use of the system method we start a child process. It is an echo bash command, which prints a message to the terminal.

In the second case we execute the bash exit command with status 1. This time we use the %x operator which executes a command between two selected delimiters. We have chosen [] characters.

The first child process terminates with status 0, the second with exit status 1.

In the final example, we show three global predefined variables that are used with regular expressions.

When we apply the =~ operator on a string, Ruby sets some variables. The $& variable has a string that matched the last last regular expression match. The $` has a string preceding $& and the $’ has a string following the $& .

In this part of the Ruby tutorial, we looked more deeply at the Ruby variables.

variable assignment ruby

Ruby has three kinds of variables, one kind of constant and exactly two pseudo-variables. The variables and the constants have no type. While untyped variables have some drawbacks, they have many more advantages and fit well with ruby's quick and easy philosophy.

Variables must be declared in most languages in order to specify their type, modifiability (i.e., whether they are constants), and scope; since type is not an issue, and the rest is evident from the variable name as you are about to see, we do not need variable declarations in ruby.

The first character of an identifier categorizes it at a glance:

The only exceptions to the above are ruby's pseudo-variables: self , which always refers to the currently executing object, and nil , which is the meaningless value assigned to uninitialized variables. Both are named as if they are local variables, but self is a global variable maintained by the interpreter, and nil is really a constant. As these are the only two exceptions, they don't confuse things too much.

You man not assign values to self or nil . main , as a value of self , refers to the top-level object:

Ruby Tutorial

  • Ruby Basics
  • Ruby - Home
  • Ruby - Overview
  • Ruby - Environment Setup
  • Ruby - Syntax
  • Ruby - Classes and Objects
  • Ruby - Variables
  • Ruby - Operators
  • Ruby - Comments
  • Ruby - IF...ELSE
  • Ruby - Loops
  • Ruby - Methods
  • Ruby - Blocks
  • Ruby - Modules
  • Ruby - Strings
  • Ruby - Arrays
  • Ruby - Hashes
  • Ruby - Date & Time
  • Ruby - Ranges
  • Ruby - Iterators
  • Ruby - File I/O
  • Ruby - Exceptions
  • Ruby Advanced
  • Ruby - Object Oriented
  • Ruby - Regular Expressions
  • Ruby - Database Access
  • Ruby - Web Applications
  • Ruby - Sending Email
  • Ruby - Socket Programming
  • Ruby - Ruby/XML, XSLT
  • Ruby - Web Services
  • Ruby - Tk Guide
  • Ruby - Ruby/LDAP Tutorial
  • Ruby - Multithreading
  • Ruby - Built-in Functions
  • Ruby - Predefined Variables
  • Ruby - Predefined Constants
  • Ruby - Associated Tools
  • Ruby Useful Resources
  • Ruby - Quick Guide
  • Ruby - Useful Resources
  • Ruby - Discussion
  • Ruby - Ruby on Rails Tutorial
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Ruby - Variables, Constants and Literals

Variables are the memory locations, which hold any data to be used by any program.

There are five types of variables supported by Ruby. You already have gone through a small description of these variables in the previous chapter as well. These five types of variables are explained in this chapter.

Ruby Global Variables

Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option.

Assignment to global variables alters the global status. It is not recommended to use global variables. They make programs cryptic.

Here is an example showing the usage of global variable.

Here $global_variable is a global variable. This will produce the following result −

NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.

Ruby Instance Variables

Instance variables begin with @. Uninitialized instance variables have the value nil and produce warnings with the -w option.

Here is an example showing the usage of Instance Variables.

Here, @cust_id, @cust_name and @cust_addr are instance variables. This will produce the following result −

Ruby Class Variables

Class variables begin with @@ and must be initialized before they can be used in method definitions.

Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

Overriding class variables produce warnings with the -w option.

Here is an example showing the usage of class variable −

Here @@no_of_customers is a class variable. This will produce the following result −

Ruby Local Variables

Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block's opening brace to its close brace {}.

When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments.

Assignment to uninitialized local variables also serves as variable declaration. The variables start to exist until the end of the current scope is reached. The lifetime of local variables is determined when Ruby parses the program.

In the above example, local variables are id, name and addr.

Ruby Constants

Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally.

Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning.

Here VAR1 and VAR2 are constants. This will produce the following result −

Ruby Pseudo-Variables

They are special variables that have the appearance of local variables but behave like constants. You cannot assign any value to these variables.

self − The receiver object of the current method.

true − Value representing true.

false − Value representing false.

nil − Value representing undefined.

__FILE__ − The name of the current source file.

__LINE__ − The current line number in the source file.

Ruby Basic Literals

The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals.

Integer Numbers

Ruby supports integer numbers. An integer number can range from -2 30 to 2 30-1 or -2 62 to 2 62-1 . Integers within this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum .

You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string.

You can also get the integer value, corresponding to an ASCII character or escape the sequence by preceding it with a question mark.

NOTE − Class and Objects are explained in a separate chapter of this tutorial.

Floating Numbers

Ruby supports floating numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following −

String Literals

Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings don't allow substitution and allow backslash notation only for \\ and \'

This will produce the following result −

You can substitute the value of any Ruby expression into a string using the sequence #{ expr } . Here, expr could be any ruby expression.

Backslash Notations

Following is the list of Backslash notations supported by Ruby −

For more detail on Ruby Strings, go through Ruby Strings .

Ruby Arrays

Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is ignored.

For more detail on Ruby Arrays, go through Ruby Arrays .

Ruby Hashes

A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value. A trailing comma is ignored.

For more detail on Ruby Hashes, go through Ruby Hashes .

Ruby Ranges

A Range represents an interval which is a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals, or with Range.new.

Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence.

A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 1, 2, 3, 4 values.

For more detail on Ruby Ranges, go through Ruby Ranges .

To Continue Learning Please Login

Ruby Tricks, Idiomatic Ruby, Refactorings and Best Practices

Conditional assignment.

Ruby is heavily influenced by lisp. One piece of obvious inspiration in its design is that conditional operators return values. This makes assignment based on conditions quite clean and simple to read.

There are quite a number of conditional operators you can use. Optimize for readability, maintainability, and concision.

If you're just assigning based on a boolean, the ternary operator works best (this is not specific to ruby/lisp but still good and in the spirit of the following examples!).

If you need to perform more complex logic based on a conditional or allow for > 2 outcomes, if / elsif / else statements work well.

If you're assigning based on the value of a single variable, use case / when A good barometer is to think if you could represent the assignment in a hash. For example, in the following example you could look up the value of opinion in a hash that looks like {"ANGRY" => comfort, "MEH" => ignore ...}

The Ruby Programming Language by David Flanagan, Yukihiro Matsumoto

Get full access to The Ruby Programming Language and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Assignments

An assignment expression specifies one or more values for one or more lvalues. lvalue is the term for something that can appear on the lefthand side of an assignment operator. (Values on the righthand side of an assignment operator are sometimes called rvalues by contrast.) Variables, constants, attributes, and array elements are lvalues in Ruby. The rules for and the meaning of assignment expressions are somewhat different for different kinds of lvalues, and each kind is described in detail in this section.

There are three different forms of assignment expressions in Ruby. Simple assignment involves one lvalue, the = operator, and one rvalue. For example:

Abbreviated assignment is a shorthand expression that updates the value of a variable by applying some other operation (such as addition) to the current value of the variable. Abbreviated assignment uses assignment operators like += and *= that combine binary operators with an equals sign:

Finally, parallel assignment is any assignment expression that has more than one lvalue or more than one rvalue. Here is a simple example:

Parallel assignment is more complicated when the number of lvalues is not the same as the number of rvalues or when there is an array on the right. Complete details follow.

The value of an assignment expression is the value (or an array of the values) assigned. Also, the assignment operator is “right-associative”—if multiple assignments appear in a single expression, they are evaluated from right to left. This means that the assignment can be chained to assign the same value to multiple variables:

Note that this is not a case of parallel assignment—it is two simple assignments, chained together: y is assigned the value 0 , and then x is assigned the value (also 0 ) of that first assignment.

Assignment and Side Effects

More important than the value of an assignment expression is the fact that assignments set the value of a variable (or other lvalue) and thereby affect program state. This effect on program state is called a side effect of the assignment.

Many expressions have no side effects and do not affect program state. They are idempotent . This means that the expression may be evaluated over and over again and will return the same value each time. And it means that evaluating the expression has no effect on the value of other expressions. Here are some expressions without side effects:

It is important to understand that assignments are not idempotent:

Some methods, such as Math.sqrt , are idempotent: they can be invoked without side effects. Other methods are not, and this largely depends on whether those methods perform assignments to nonlocal variables.

Assigning to Variables

When we think of assignment, we usually think of variables, and indeed, these are the most common lvalues in assignment expressions. Recall that Ruby has four kinds of variables: local variables, global variables, instance variables, and class variables. These are distinguished from each other by the first character in the variable name. Assignment works the same for all four kinds of variables, so we do not need to distinguish between the types of variables here.

Keep in mind that the instance variables of Ruby’s objects are never visible outside of the object, and variable names are never qualified with an object name. Consider this assignment:

The lvalues in this expression are not variables; they are attributes, and are explained shortly.

Assignment to a variable works as you would expect: the variable is simply set to the specified value. The only wrinkle has to do with variable declaration and an ambiguity between local variable names and method names. Ruby has no syntax to explicitly declare a variable: variables simply come into existence when they are assigned. Also, local variable names and method names look the same—there is no prefix like $ to distinguish them. Thus, a simple expression such as x could refer to a local variable named x or a method of self named x . To resolve this ambiguity, Ruby treats an identifier as a local variable if it has seen any previous assignment to the variable. It does this even if that assignment was never executed. The following code demonstrates:

Assigning to Constants

Constants are different from variables in an obvious way: their values are intended to remain constant throughout the execution of a program. Therefore, there are some special rules for assignment to constants:

Assignment to a constant that already exists causes Ruby to issue a warning. Ruby does execute the assignment, however, which means that constants are not really constant.

Assignment to constants is not allowed within the body of a method. Ruby assumes that methods are intended to be invoked more than once; if you could assign to a constant in a method, that method would issue warnings on every invocation after the first. So, this is simply not allowed.

Unlike variables, constants do not come into existence until the Ruby interpreter actually executes the assignment expression. A nonevaluated expression like the following does not create a constant:

Note that this means a constant is never in an uninitialized state. If a constant exists, then it has a value assigned to it. A constant will only have the value nil if that is actually the value it was given.

Assigning to Attributes and Array Elements

Assignment to an attribute or array element is actually Ruby shorthand for method invocation. Suppose an object o has a method named m= : the method name has an equals sign as its last character. Then o.m can be used as an lvalue in an assignment expression. Suppose, furthermore, that the value v is assigned:

The Ruby interpreter converts this assignment to the following method invocation:

That is, it passes the value v to the method m= . That method can do whatever it wants with the value. Typically, it will check that the value is of the desired type and within the desired range, and it will then store it in an instance variable of the object. Methods like m= are usually accompanied by a method m , which simply returns the value most recently passed to m= . We say that m= is a setter method and m is a getter method. When an object has this pair of methods, we say that it has an attribute m . Attributes are sometimes called “properties” in other languages. We’ll learn more about attributes in Ruby in Accessors and Attributes .

Assigning values to array elements is also done by method invocation. If an object o defines a method named []= (the method name is just those three punctuation characters) that expects two arguments, then the expression o[x] = y is actually executed as:

If an object has a []= method that expects three arguments, then it can be indexed with two values between the square brackets. The following two expressions are equivalent in this case:

Abbreviated Assignment

Abbreviated assignment is a form of assignment that combines assignment with some other operation. It is used most commonly to increment variables:

+= is not a real Ruby operator, and the expression above is simply an abbreviation for:

Abbreviated assignment cannot be combined with parallel assignment: it only works when there is a single lvalue on the left and a single value on the right. It should not be used when the lvalue is a constant because it will reassign the constant and cause a warning. Abbreviated assignment can, however, be used when the lvalue is an attribute. The following two expressions are equivalent:

Abbreviated assignment even works when the lvalue is an array element. These two expressions are equivalent:

Note that this code uses -= instead of += . As you might expect, the -= pseudooperator subtracts its rvalue from its lvalue.

In addition to += and -= , there are 11 other pseudooperators that can be used for abbreviated assignment. They are listed in Table 4-1 . Note that these are not true operators themselves, they are simply shorthand for expressions that use other operators. The meanings of those other operators are described in detail later in this chapter. Also, as we’ll see later, many of these other operators are defined as methods. If a class defines a method named + , for example, then that changes the meaning of abbreviated assignment with += for all instances of that class.

Table 4-1. Abbreviated assignment pseudooperators

The ||= Idiom

As noted at the beginning of this section, the most common use of abbreviated assignment is to increment a variable with += . Variables are also commonly decremented with -= . The other pseudooperators are much less commonly used. One idiom is worth knowing about, however. Suppose you are writing a method that computes some values, appends them to an array, and returns the array. You want to allow the user to specify the array that the results should be appended to. But if the user does not specify the array, you want to create a new, empty array. You might use this line:

Think about this for a moment. It expands to:

If you know the || operator from other languages, or if you’ve read ahead to learn about || in Ruby, then you know that the righthand side of this assignment evaluates to the value of results , unless that is nil or false . In that case, it evaluates to a new, empty array. This means that the abbreviated assignment shown here leaves results unchanged, unless it is nil or false , in which case it assigns a new array.

The abbreviated assignment operator ||= actually behaves slightly differently than the expansion shown here. If the lvalue of ||= is not nil or false , no assignment is actually performed. If the lvalue is an attribute or array element, the setter method that performs assignment is not invoked.

Parallel Assignment

Parallel assignment is any assignment expression that has more than one lvalue, more than one rvalue, or both. Multiple lvalues and multiple rvalues are separated from each other with commas. lvalues and rvalues may be prefixed with * , which is sometimes called the splat operator , though it is not a true operator. The meaning of * is explained later in this section.

Most parallel assignment expressions are straightforward, and it is obvious what they mean. There are some complicated cases, however, and the following subsections explain all the possibilities.

Same number of lvalues and rvalues

Parallel assignment is at its simplest when there are the same number of lvalues and rvalues:

In this case, the first rvalue is assigned to the first lvalue; the second rvalue is assigned to the second lvalue; and so on.

These assignments are effectively performed in parallel, not sequentially. For example, the following two lines are not the same:

One lvalue, multiple rvalues

When there is a single lvalue and more than one rvalue, Ruby creates an array to hold the rvalues and assigns that array to the lvalue:

You can place an * before the lvalue without changing the meaning or the return value of this assignment.

If you want to prevent the multiple rvalues from being combined into a single array, follow the lvalue with a comma. Even with no lvalue after that comma, this makes Ruby behave as if there were multiple lvalues:

Multiple lvalues, single array rvalue

When there are multiple lvalues and only a single rvalue, Ruby attempts to expand the rvalue into a list of values to assign. If the rvalue is an array, Ruby expands the array so that each element becomes its own rvalue. If the rvalue is not an array but implements a to_ary method, Ruby invokes that method and then expands the array it returns:

The parallel assignment has been transformed so that there are multiple lvalues and zero (if the expanded array was empty) or more rvalues. If the number of lvalues and rvalues are the same, then assignment occurs as described earlier in Same number of lvalues and rvalues . If the numbers are different, then assignment occurs as described next in Different numbers of lvalues and rvalues .

We can use the trailing-comma trick described above to transform an ordinary nonparallel assignment into a parallel assignment that automatically unpacks an array on the right:

Different numbers of lvalues and rvalues

If there are more lvalues than rvalues, and no splat operator is involved, then the first rvalue is assigned to the first lvalue, the second rvalue is assigned to the second lvalue, and so on, until all the rvalues have been assigned. Next, each of the remaining lvalues is assigned nil , overwriting any existing value for that lvalue:

If there are more rvalues than lvalues, and no splat operator is involved, then rvalues are assigned—in order—to each of the lvalues, and the remaining rvalues are discarded:

The splat operator

When an rvalue is preceded by an asterisk, it means that that value is an array (or an array-like object) and that its elements should each be rvalues. The array elements replace the array in the original rvalue list, and assignment proceeds as described above:

In Ruby 1.8, a splat may only appear before the last rvalue in an assignment. In Ruby 1.9, the list of rvalues in a parallel assignment may have any number of splats, and they may appear at any position in the list. It is not legal, however, in either version of the language, to attempt a “double splat” on a nested array:

Array, range and hash rvalues can be splatted. In general, any rvalue that defines a to_a method can be prefixed with a splat. Any Enumerable object, including enumerators (see Enumerators ) can be splatted, for example. When a splat is applied to an object that does not define a to_a method, no expansion is performed and the splat evaluates to the object itself.

When an lvalue is preceded by an asterisk, it means that all extra rvalues should be placed into an array and assigned to this lvalue. The value assigned to that lvalue is always an array, and it may have zero, one, or more elements:

In Ruby 1.8, a splat may only precede the last lvalue in the list. In Ruby 1.9, the lefthand side of a parallel assignment may include one splat operator, but it may appear at any position in the list:

Note that splats may appear on both sides of a parallel assignment expression:

Finally, recall that earlier we described two simple cases of parallel assignment in which there is a single lvalue or a single rvalue. Note that both of these cases behave as if there is a splat before the single lvalue or rvalue. Explicitly including a splat in these cases has no additional effect.

Parentheses in parallel assignment

One of the least-understood features of parallel assignment is that the lefthand side can use parentheses for “subassignment.” If a group of two or more lvalues is enclosed in parentheses, then it is initially treated as a single lvalue. Once the corresponding rvalue has been determined, the rules of parallel assignment are applied recursively—that rvalue is assigned to the group of lvalues that was in parentheses. Consider the following assignment:

This is effectively two assignments executed at the same time:

But note that the second assignment is itself a parallel assignment. Because we used parentheses on the lefthand side, a recursive parallel assignment is performed. In order for it to work, b must be a splattable object such as an array or enumerator.

Here are some concrete examples that should make this clearer. Note that parentheses on the left act to “unpack” one level of nested array on the right:

The value of parallel assignment

The return value of a parallel assignment expression is the array of rvalues (after being augmented by any splat operators).

Parallel Assignment and Method Invocation

As an aside, note that if a parallel assignment is prefixed with the name of a method, the Ruby interpreter will interpret the commas as method argument separators rather than as lvalue and rvalue separators. If you want to test the return value of a parallel assignment, you might write the following code to print it out:

This doesn’t do what you want, however; Ruby thinks you’re invoking the puts method with three arguments: x , y=1 , and 2 . Next, you might try putting the parallel assignment within parentheses for grouping:

This doesn’t work, either; the parentheses are interpreted as part of the method invocation (though Ruby complains about the space between the method name and the opening parenthesis). To actually accomplish what you want, you must use nested parentheses:

This is one of those strange corner cases in the Ruby grammar that comes as part of the expressiveness of the grammar. Fortunately, the need for syntax like this rarely arises.

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

variable assignment ruby

Ruby 2.1 - Fun with underscores, ampersands and asterisks

By matthias geier.

Variable assignment in Ruby is a flexible thing. It allows you to do helpful things and once you realize that function calls are not much different from variable assignments, things become much easier and the code becomes clearer. (Of course, internally a function call is not the same as a variable assignment, yet its behaviour is similar, which is what I am referring to).

Variable assignment

Starting with a simple example that can make array assignment beautiful.

This works for as many variables as you need, even when the array size differs.

Ruby by default assigns nil to all variables it cannot find a match to.

As you can see, subsets work too.

Having worked so far with only named variables, introducing the underscore will allow you to skip elements you do not need.

The underscore adds as a placeholder for the variable matching inside Ruby. It is just as greedy as any named variable, but as it is not named, you cannot access it later on. This works of course with the earlier examples too, when you only need a subset or have a smaller count of array elements.

In blocks it is possible to split an array into multiple variables by putting the variables in parentheses. It is possible to skip elements with the underscore again too, just like with regular array assignments from earlier.

Making things more complex and introducing the asterisk, which allows the collection of remaining elements from an assignment. The representation for the asterisk variable is always an array, whether it gets elements assigned or not.

Ruby only allows you to add one asterisk variable to the assignment which acts as an array container for elements. The position of the asterisk variable is flexible and does not need to be at the end.

Of course you can also add underscores. Additionally, Ruby allows the combination of both underscore and asterisk which is especially useful when you need for instance the first and last element from an array.

The asterisk is also used for dereferencing variables. Later on in function calls it will be used to pass the array content to a function as parameters. Using the asterisk on a Hash will produce a slightly different behaviour, it is more or less an alias on to_a.

Function calls

Moving on to function calls. As I mentioned earlier, in Ruby a function call behaves similar to the variable assignment we have been doing for the earlier part of the article. Function calls have some quirks though which will be discussed in the next section.

Applying variable assignment

When using function calls in Ruby, there is the regular call, in which you call the function by name and hand it all the parameters it requires.

Or you can use what you know from the asterisk assignment and pass it an array.

Of course you can use one array for all arguments. The main issue you have to take care of here is that each element of the array being passed is used as one assignment. The parameters have to match the amount the function actually requires, otherwise Ruby will throw an ArgumentError.

What worked in blocks earlier, of course works here as well.

Next up would be the underscore. The usefulness is a little questionable, but thinking back I can recall one or two examples when it made sense. Remember that an underscore is an unnamed variable and acts just as greedy as any other named.

Collecting remaining arguments and therefore avoiding any ArgumentError can be achieved by using the asterisk again. The placement of the asterisk is, similar to variable assignment, up to you.

Default values

Of course this is not the end of it. Ruby allows you to define defaults for any parameter of the function. There are two rules to follow. First you need to group all parameters that have a default together, you cannot split them. Second is that default values are not greedy.

It is possible to also add an asterisk parameter to a function with defaults. The asterisk parameter needs to be defined after the block with all defaults, that is mandatory. That asterisk parameter ends up to be the least greedy. First up all required parameters are satisfied, then from left to right all defaults and whatever remains is put into the asterisk parameter.

Conventionally it may make sense to order your parameters in such a way, that all required are first, then all defaults and the asterisk after that.

Methods and procs (that also works for lambdas) can be shortened or passed into function by using the ampersand character. I have identified two usages that I frequently use and increase readability and structure.

Method shortening is probably used in over half of the map calls I make in Rails. It essentially hands the map a symbol of the method the map should call on every element of an array. This can be any method name that takes no parameters (defaults are fine) and map will raise you a NoMethodError or ArgumentError should something go wrong.

It is also possible to define your own block using a proc or lambda and pass that instead of defining your do…end in place.

This can be especially useful when you have the same block you need to use over and over again.

Final thoughts

Ruby offers a set of tools that allow you to make your code readable and explicit. It’d be a shame not to use them. I am especially a fan of the variable assignment options, as they usually save me multiple lines of splitting arrays into variables that have meaningful names.

  • variable assignment 1
  • special characters 1
  • ← Previous
  • Next →

IMAGES

  1. A (Super) Brief Intro to Python

    variable assignment ruby

  2. Beginner Ruby

    variable assignment ruby

  3. សិក្សាលំអិតអំពីអញ្ញត្តិ (Variables) និងការផ្តល់តំលៃឲ្យ (Assignment

    variable assignment ruby

  4. The Basics of Variable Assignment in Ruby

    variable assignment ruby

  5. [Solved] Double Pipe Symbols in Ruby Variable Assignment?

    variable assignment ruby

  6. [Solved] Ruby: Use the return of the conditional for

    variable assignment ruby

VIDEO

  1. Ruby understands the assignment (Bfdia 7 re- animated)

  2. Hunter assignment Ruby game boys double attitude

  3. Ruby Todman KPB117 2024 n11224258

  4. Hunter assignment Ruby game

  5. 6 storing values in variable, assignment statement

  6. Hunter assignment Ruby game boys attitude

COMMENTS

  1. Ruby Variables: A Beginner's Guide

    You create variables by associating a Ruby object with a variable name. We call this "variable assignment". Example: age = 32. Now when you type age Ruby will translate that into 32. Try it! There is nothing special about the word age. You could use bacon = 32 & the value would still be 32. Variables are just names for things.

  2. assignment

    Assignment. In Ruby, assignment uses the = (equals sign) character. This example assigns the number five to the local variable v: v = 5. Assignment creates a local variable if the variable was not previously referenced. An assignment expression result is always the assigned value, including assignment methods.

  3. The Basics of Variable Assignment in Ruby

    Let's start with the most basic of basics, the assigning of variables to barewords: a = "Ruby". In the above code, we have assigned a value of "Ruby" to the bareword a, which tells our ...

  4. ruby

    Yes, it will. It's an instance variable. In ruby, if you prefix your variable with @, it makes the variable an instance variable that will be available outside the block. In addition to that, Ruby does not have block scope (block in the traditional sense, if/then/else in this case).

  5. Variables

    Let's jump right in: In Ruby you can assign a name to something (an object) by using the so called assignment operator =. Like so: number = 1. This will assign the name number to the "thing" (object) that is the number 1. From now on we can refer to this object by using the name number. For example the following code would output the ...

  6. Variables

    Describe what a variable is and how to assign it a value or expression. Explain what the +=, -=, *=, and /= assignment operators do. Describe the naming conventions for variables. Declaring a variable. This is how to create a variable in Ruby: age = 18 #=> 18 You can also assign the result of an expression to a variable. age = 18 + 5 #=> 23

  7. assignment

    Assignment ¶ ↑. In Ruby assignment uses the = (equals sign) character. This example assigns the number five to the local variable v: v = 5. Assignment creates a local variable if the variable was not previously referenced. Local Variable Names ¶ ↑. A local variable name must start with a lowercase US-ASCII letter or a character with the ...

  8. Assignment

    In Ruby, assignment uses the = (equals sign) character. This example assigns the number five to the local variable v: v = 5. Assignment creates a local variable if the variable was not previously referenced. Abbreviated Assignment. You can mix several of the operators and assignment. To add 1 to an object you can write:

  9. Ruby variables

    Ruby pseudo variables. Ruby has a few variables which are called pseudo variables. They are different from regular variables. We cannot assign values to pseudo variables. The self is the receiver of the current method. The nil is the sole instance of the NilClass. It represents the absense of a value. The true is the sole instance of the ...

  10. Variables

    The only exceptions to the above are ruby's pseudo-variables: self, which always refers to the currently executing object, and nil, which is the meaningless value assigned to uninitialized variables.Both are named as if they are local variables, but self is a global variable maintained by the interpreter, and nil is really a constant. As these are the only two exceptions, they don't confuse ...

  11. Ruby

    These five types of variables are explained in this chapter. Ruby Global Variables. Global variables begin with &dollar;. Uninitialized global variables have the value nil and produce warnings with the -w option. Assignment to global variables alters the global status. It is not recommended to use global variables. They make programs cryptic.

  12. Ruby

    A variable is a label that Ruby assigns to a particular object. There are four different types of variables in Ruby. Each type starts with a special character to indicate the type of variable it is. Local variables must begin with a lowercase letter or . These variables are local to the code block of the method they are declared in. ruby color ...

  13. Official Ruby FAQ

    a = 1. method `a' called. a = 99. During the parse, Ruby sees the use of a in the first puts statement and, as it hasn't yet seen any assignment to a, assumes that it is a method call. By the time it gets to the second puts statement, though, it has seen an assignment, and so treats a as a variable.

  14. Variable References

    Variables are created and values assigned to them by assignment expressions, which are covered later in this chapter. When the name of a variable appears in a program anywhere other than the lefthand side of an assignment, it is a variable reference expression and evaluates to the value of the variable: one = 1.0 # This is an assignment expression.

  15. Conditional assignment

    Conditional assignment. Ruby is heavily influenced by lisp. One piece of obvious inspiration in its design is that conditional operators return values. This makes assignment based on conditions quite clean and simple to read. ... If you're assigning based on the value of a single variable, use case/when A good barometer is to think if you could ...

  16. Assignments

    An assignment expression specifies one or more values for one or more lvalues. lvalue is the term for something that can appear on the lefthand side of an assignment operator. (Values on the righthand side of an assignment operator are sometimes called rvalues by contrast.) Variables, constants, attributes, and array elements are lvalues in Ruby.

  17. Is assignment in a conditional clause good ruby style?

    The reason it's bad is because it's usually the case that you are doing a straight up equality check in a conditional (with == ), and assignment ( =) is a common typo. Requiring surrounding parentheses when you do assignment in conditional is an extra hint to the reader that the assignment was INTENTIONAL, not a typo. - Devon Parsons.

  18. Ruby 2.1

    Variable assignment in Ruby is a flexible thing. It allows you to do helpful things and once you realize that function calls are not much different from variable assignments, things become much easier and the code becomes clearer. (Of course, internally a function call is not the same as a variable assignment, yet its behaviour is similar ...

  19. How to do multiple assignment with return values in ruby (1.9) case

    Yes, there is a parallel assignment in your first sample ( limit,pattern = q[0],q[1] ). But when you try to involve a case expression, it stops being one. By the way, you could simply write limit, pattern = q. indeed, but it would be more the ruby way if the intent (on the left hand side of the =) would be reflected in the the syntax of writing ...

  20. ruby

    As Yu mentioned, the right hand side of the assignment is returned as the value of the assignment expression, meaning the result of socket.gets.split(' ',2) is evaluated for truthiness. This will always evaluate as true. The result of the operation is then set to the variable line within the scope of the while. break if line[0] == ""

  21. ruby

    ruby unintended variable assignment/change. 0. How can a variable have a value and also not be defined? 0. Ruby - Why is a variable a valid statement? 8. Ruby variable assignment. 0. How does variable assignment works in ruby? Hot Network Questions Is the Sufficiency Principle an axiom?