Expressions

Operator expressions, miscellaneous expressions, command expansion, backquotes are soft, parallel assignment, nested assignments, other forms of assignment, conditional execution, boolean expressions, defined, and, or, and not, if and unless expressions, if and unless modifiers, case expressions, break, redo, and next, variable scope and loops.

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:

Conditionals

if statements allow you to take different actions depending on which conditions are met. For example:

  • if the city is equal to ( == ) "Toronto" , then set drinking_age to 19.
  • Otherwise ( else ) set drinking_age to 21.

true and false

Ruby has a notion of true and false. This is best illustrated through some example. Start irb and type the following:

The if statements evaluates whether the expression (e.g. ' city == "Toronto" ) is true or false and acts accordingly.

Most common conditionals

Here is a list of some of the most common conditionals:

String comparisons

How do these operators behave with strings? Well, == is string equality and > and friends are determined by ASCIIbetical order.

What is ASCIIbetical order? The ASCII character table contains all the characters in the keyboard. It lists them in this order:

Start irb and type these in:

elsif allows you to add more than one condition. Take this for example:

Let's go through this:

  • If age is 60 or more, we give a senior fare.
  • If that's not true, but age is 14 or more, we give the adult fare.
  • If that's not true, but age is more than 2 we give the child fare.
  • Otherwise we ride free.

Ruby goes through this sequence of conditions one by one. The first condition to hold gets executed. You can put as many elsif 's as you like.

Example - fare_finder.rb

To make things more clear, let's put this in a program. The program asks for your age and gives you the corresponding fare.

Type this in and run it. It should behave like this:

This will output:

Here age is both greater than 10 and greater than 20. Only the first statement that holds true gets executed.

The correct way to write this would be:

Re-arrange these characters in ASCIIbetical order:

The ASCII table contains all the characters in the keyboard. Use irb to find out wheter the characters "?" lies:

  • After 9 but before A.
  • After Z but before a.

Using your experience the previous question, make a program that accepts a character input and tells you if the character lines:

Then try the program with the following characters:

Sample answers:

  • $ lies before 0
  • < lies between 9 and A
  • - lies between Z and a
  • ~ lies after z

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.

assignment statements in ruby

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 ...}

CodingDrills logo

Conditional Statements in Ruby

Conditional statements are an essential part of any programming language, including Ruby. They give us the ability to make decisions and alter the flow of our code based on certain conditions. In this tutorial, we will delve into the basics of conditional statements in Ruby, exploring various types and their usage.

If Statements

The most basic form of a conditional statement is the if statement. It allows us to execute a block of code only if a certain condition is met.

Here is a simple example:

In this example, we first declare a variable age with a value of 25. The if statement checks whether age is greater than 18. If the condition evaluates to true, the code inside the if block is executed, and the message "You are an adult!" is printed.

We can also add an else block after the if block to handle cases when the condition is not met. Taking the previous example further:

In this case, since age is 16, the condition age > 18 is false, and thus the code in the else block is executed, printing "You are not yet an adult."

ElseIf Statements

Ruby provides the elsif statement as a way to add additional conditions to our if statements. This allows us to handle multiple possible outcomes in a more organized manner.

Consider the following example:

In this example, we have multiple conditions. If age is less than 18, the first if block is executed. If not, the program checks the next condition using the elsif keyword. If age is between 18 and 65, the second elsif block is executed. Finally, if none of the previous conditions are met, the code inside the else block is executed.

Case Statements

Another way to handle conditional statements in Ruby is by using case statements. These statements can be helpful when dealing with multiple possible values for a variable.

Here is an example:

In this case statement, we check the value of the variable day . Depending on its value, different code blocks are executed. In this example, since day is "Monday," the code inside the first when block is executed, printing "It's the beginning of the week."

Case statements also support ranges and multiple conditions for each when block. They are a flexible tool for handling complex conditional logic.

Conditional statements are a crucial aspect of programming in any language, and Ruby is no exception. They provide us with the ability to control the flow of our code based on specific conditions. In this tutorial, we explored the basics of conditional statements in Ruby, including if statements, elsif statements for multiple conditions, and case statements for handling various possible values.

With the knowledge gained from this tutorial, you are now equipped to use conditional statements effectively in your Ruby programs. Happy coding!

Remember to save this Markdown file and convert it to HTML using your preferred Markdown converter to properly format and present the content on your blog.

CodingDrills logo

Hi, I'm Ada, your personal AI tutor. I can help you with any coding tutorial. Go ahead and ask me anything.

I have a question about this topic

Give more examples

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Ruby Programming Language
  • Ruby For Beginners
  • Ruby Programming Language (Introduction)
  • Comparison of Java with other programming languages
  • Similarities and Differences between Ruby and C language
  • Similarities and Differences between Ruby and C++
  • Environment Setup in Ruby
  • How to install Ruby on Linux?
  • How to install Ruby on Windows?
  • Interesting facts about Ruby Programming Language
  • Ruby | Keywords
  • Ruby | Data Types
  • Ruby Basic Syntax
  • Hello World in Ruby
  • Ruby | Types of Variables
  • Global Variable in Ruby
  • Comments in Ruby
  • Ruby | Ranges
  • Ruby Literals
  • Ruby Directories
  • Ruby | Operators
  • Operator Precedence in Ruby
  • Operator Overloading in Ruby
  • Ruby | Pre-define Variables & Constants
  • Ruby | unless Statement and unless Modifier

Control Statements

  • Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
  • Ruby | Loops (for, while, do..while, until)
  • Ruby | Case Statement
  • Ruby | Control Flow Alteration
  • Ruby Break and Next Statement
  • Ruby redo and retry Statement
  • BEGIN and END Blocks In Ruby
  • File Handling in Ruby
  • Ruby | Methods
  • Method Visibility in Ruby
  • Recursion in Ruby
  • Ruby Hook Methods
  • Ruby | Range Class Methods
  • The Initialize Method in Ruby
  • Ruby | Method overriding
  • Ruby Date and Time

OOP Concepts

  • Object-Oriented Programming in Ruby | Set 1
  • Object Oriented Programming in Ruby | Set-2
  • Ruby | Class & Object
  • Private Classes in Ruby
  • Freezing Objects | Ruby
  • Ruby | Inheritance
  • Polymorphism in Ruby
  • Ruby | Constructors
  • Ruby | Access Control
  • Ruby | Encapsulation
  • Ruby Mixins
  • Instance Variables in Ruby
  • Data Abstraction in Ruby
  • Ruby Static Members
  • Ruby | Exceptions
  • Ruby | Exception handling
  • Catch and Throw Exception In Ruby
  • Raising Exceptions in Ruby
  • Ruby | Exception Handling in Threads | Set - 1
  • Ruby | Exception Class and its Methods
  • Ruby | Regular Expressions
  • Ruby Search and Replace

Ruby Classes

  • Ruby | Float Class
  • Ruby | Integer Class
  • Ruby | Symbol Class
  • Ruby | Struct Class
  • Ruby | Dir Class and its methods
  • Ruby | MatchData Class

Ruby Module

  • Ruby | Module
  • Ruby | Comparable Module
  • Ruby | Math Module
  • Include v/s Extend in Ruby

Collections

  • Ruby | Arrays
  • Ruby | String Basics
  • Ruby | String Interpolation
  • Ruby | Hashes Basics
  • Ruby | Hash Class
  • Ruby | Blocks

Ruby Threading

  • Ruby | Introduction to Multi-threading
  • Ruby | Thread Class-Public Class Methods
  • Ruby | Thread Life Cycle & Its States

Miscellaneous

  • Ruby | Types of Iterators
  • Ruby getters and setters Method

Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set – 1

Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Similarly, in Ruby, the if-else statement is used to test the specified condition. 

Decision-Making Statements in Ruby:  

if statement

  • if-else statement
  • if – elsif ladder
  • Ternary statement

If statement in Ruby is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

Flowchart:  

assignment statements in ruby

Output:  

if – else Statement

In this ‘if’ statement used to execute block of code when the condition is true and ‘else’ statement is used to execute a block of code when the condition is false.

Syntax:   

assignment statements in ruby

Example:   

If – elsif – else ladder Statement

Here, a user can decide among multiple options. ‘if’ statements are executed from the top down. As soon as one of the conditions controlling the ‘if’ is true, the statement associated with that ‘if’ is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

assignment statements in ruby

Ternary Statement

In Ruby ternary statement is also termed as the shortened if statement . It will first evaluate the expression for true or false value and then execute one of the statements. If the expression is true, then the true statement is executed else false statement will get executed.

Syntax:  

author

Please Login to comment...

Similar reads.

  • Ruby-Basics
  • Ruby-Decision-Making

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Ruby Programming

assignment statements in ruby

Ruby is an interpreted , object-oriented programming language. Its creator, Yukihiro Matsumoto , aka “Matz”, released it to the public in 1995. Its history is covered here . Its many features are listed here .

The book is currently broken down into several sections and is intended to be read sequentially. Getting started will show how to install and get started with Ruby in your environment. Basic Ruby demonstrates the main features of the language syntax. The Ruby language section is organized like a reference to the language. Available modules covers some of the standard library. Intermediate Ruby covers a selection of slightly more advanced topics. Each section is designed to be self contained.

Table of Contents [ edit | edit source ]

Getting started [ edit | edit source ], basic ruby [ edit | edit source ], ruby semantic reference [ edit | edit source ].

  • Identifiers
  • Embedded Documentation
  • Reserved Words
  • Expressions
  • Local Variables
  • Instance Variables
  • Class Variables
  • Global Variables
  • Pseudo Variables
  • Pre-defined Variables
  • Interpolation
  • Backslash Notation
  • The % Notation
  • Command Expansion
  • Regular Expressions
  • Self Assignment
  • Multiple Assignment
  • Conditional Assignment
  • if modifier
  • unless modifier
  • while modifier
  • until modifier
  • rescue modifier
  • Class Methods
  • Instantiation
  • Inheritance
  • Mixing in Modules
  • Ruby Class Meta-Model
  • Ruby Hooks add the ability to know when new methods are defined et al.

See also some rdoc documentation on the various keywords.

Built in Classes [ edit | edit source ]

This is a list of classes that are available to you by default in Ruby. They are pre-defined in “core.”

  • Built-in Functions
  • Enumerable::Enumerator
  • GC::Profiler
  • Struct::Tms

Available Standard Library Modules [ edit | edit source ]

These are parts of Ruby that you have available (in the standard library, or via installation as a gem). To use them you typically have to require some filename, for example require 'tracer' would make accessible to you the Tracer class.

You can see a list of basically all the (std lib ruby) modules available in the ruby source and lib readme . There are a several more modules available in the std lib, which are C based extensions. You can see their list here .

  • BigDecimal gives you a way to have arbitrary precision Decimal style numbers. Never succumb to rounding errors again!
  • Debugger gives you a way to step through debug your Ruby code.
  • Distributed Ruby (DRb) gives you a way to make remote procedure calls against objects in a different VM.
  • mkmf is a utility used to generate makefiles for ruby extensions.
  • Mutex gives you a way to control thread concurrency.
  • Net::HTTP gives you a way to download web pages.
  • Open3 gives you a way to run a sub-process and have easy access to its I/O.
  • OpenSSL is a wrapper to the OpenSSL (C) library, giving you access to secure socket connections.
  • Pathname gives you an easy way to manipulate filenames and create/remove files.
  • Profiler gives you a way to profile what is taking up the most time in your code.
  • OpenURI gives you a way to download files using ruby.
  • REXML is a way to parse XML in pure Ruby.
  • Ripper gives you a way to parse pure Ruby code into an AST.
  • Socket gives you access to Network connectivity.
  • Tracer gives you a way to see which lines of your code are being executed and in what order.
  • Win32::Registry gives you a way to query and edit the windows registry.
  • Win32API gives you a way to call into specific windows core methods easily.
  • WIN32OLE gives you a way to use Windows OLE.

Other Libraries [ edit | edit source ]

  • Database Interface Modules

GUI Libraries [ edit | edit source ]

  • GUI Toolkit Modules gives a run down of various options for ruby GUI programming.

Here is info on some specifically:

  • GTK2 Notes on the GTK/Gnome bindings.

Intermediate Ruby [ edit | edit source ]

Here are some more in depth tutorials of certain aspects of Ruby.

External links [ edit | edit source ]

  • Ruby homepage
  • Access to various Ruby mailing lists
  • Various open-source Ruby projects

Documentation [ edit | edit source ]

Core docs [ edit | edit source ].

  • Ruby Documentation Homepage - various ruby documentations and tutorials, as well as information on how to update ruby's core docs should you so desire.

gem docs [ edit | edit source ]

  • Ruby Toolbox - Find actively maintained & popular open source software libraries for the Ruby programming language

Learning Ruby [ edit | edit source ]

  • Ruby in Twenty Minutes - A small Ruby tutorial
  • CK-12 - Online Ruby tutorials & practice exercises
  • Learning Ruby A free tool to find and learn Ruby concepts using flash cards.

Books [ edit | edit source ]

Print [ edit | edit source ].

  • The Ruby Programming Language by David Flanagan, Yukihiro Matsumoto aka “Matz,” the creator of Ruby. Also covers 1.9
  • Programming Ruby 1.9 & 2.0 (aka “Pickaxe”) by Dave Thomas, with Chad Fowler and Andy Hunt — this 2013 version covers Ruby 1.9 and 2.0
  • Programming Ruby 3.2 by Noel Rappin, with Dave Thomas
  • Ruby by Example

Online [ edit | edit source ]

  • Programming Ruby (a.k.a. “Pickaxe”) 1st edition online version
  • Why’s (Poignant) Guide To Ruby
  • Humble Little Ruby Book

Quick References [ edit | edit source ]

  • Ruby Quick Reference (some of more obscure expressions are explained)
  • Ruby Cheat Sheets (a list of some different Ruby cheat sheets)

assignment statements in ruby

  • Book:Ruby Programming
  • Shelf:Ruby programming language
  • Books with print version
  • Books with PDF version
  • Subject:Ruby programming language
  • Subject:Ruby programming language/all books
  • Subject:Computer programming languages/all books
  • Subject:Computer programming/all books
  • Subject:Computer science/all books
  • Subject:Computing/all books
  • Subject:Books by subject/all books
  • Book:Wikibooks Stacks/Books
  • Shelf:Ruby programming language/all books
  • Shelf:Computer programming/all books
  • Shelf:Computer programming languages/all books
  • Shelf:Computer science/all books
  • Department:Computing/all books
  • Alphabetical/R
  • Half-finished books
  • Books by completion status/all books

Navigation menu

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons

Margin Size

  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

1.6.1: More About Valid Variable Names

  • Last updated
  • Save as PDF
  • Page ID 87272

  • Carey Smith
  • Oxnard College

\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

\( \newcommand{\Span}{\mathrm{span}}\)

\( \newcommand{\id}{\mathrm{id}}\)

\( \newcommand{\kernel}{\mathrm{null}\,}\)

\( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\)

\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\)

\( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

\( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vectorC}[1]{\textbf{#1}} \)

\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

Variable Name Rules

MATLAB variable names must start with a letter. The rest of the name can be letters, numbers or the underscore symbol. The letters can be upper or lower case. These are valid variable names:

b, B, Basketball, Basket_Ball, basket5ball, basketBall_12345

These are not valid names:

Basket-Ball, Basket_Ball!, Basket?Ball, Basket Ball.

Descriptive names are encouraged, in order to make the code readable. So 'pressure' and 'press' are better names than just 'p'. Names are allowed to be very long, but they should not be more than a quarter of the command window, so keep them to less than 20 letters, unless there is a very good reason to make them longer. (The maximumn allowed name length is 63 characters.)

Sometimes, you may have 2 version of the same quantity, such as a distance in both inches and centimeters. A good practice is to give them related names with identifiers, such as dist_inch and dist_cm, so that you always know which units you are using.

Variable Names to Avoid

Don't use the name of a function. For example, don't use these names:

sqrt, sin, cos, log10, sum.

Also, don't use 2 names that only differ for upper vs. lower case letters; that can lead to confusion. For example, having 2 variables named kg and Kg should be avoided.

Exercise \(\PageIndex{1}\) Good Variable Names

Which of the following are good variable names? Make a decision about each before looking at the answers.

You may enter each in the command window by setting the name = 1, in order to see if it is valid.

You may use the exist() function to see if it is a function name.

A-very_long_name

Even_123_longer456_name_9876543210

sind -- a function name--don't use it

sinx -- valid

A-very_long_name -- not valid becuz of the -, which is interpreted as a minus sign

Even_123_longer456_name_9876543210 -- valid

important! -- nor valid becuz of the !

_next -- not valid. It can't start with an underscore

1one1 -- not valid. It can't start with a number

MATLAB keywords

It is not allowed to use MATLAB keywords. These are words that MATLAB reserves for program structure. This is the list of keywords:

'break' 'case' 'catch' 'classdef' 'continue' 'else' 'elseif' 'end' 'for' 'function' 'global' 'if' 'otherwise' 'parfor' 'persistent' 'return' 'spmd' 'switch' 'try' 'while'

assignment statements in ruby

ARDOT to Host Location and Design Public Hearing for Proposed Widening of Highway 82 from Hamburg to Montrose

  • PUBLISHED Date: May 28, 2024

ASHLEY COUNTY | May 28, 2024

The Arkansas Department of Transportation (ARDOT) and the Federal Highway Administration (FHWA) will conduct a Location and Design Public Hearing in Hamburg Thursday, June 27 from 4-7 p.m. to present and discuss the design plans and the Environmental Assessment (EA) for the proposed widening of Highway 82 from Hamburg to Montrose in Ashley County.

The meeting will be held at First Baptist Church (Fellowship Hall), 203 E Parker Street, Hamburg, AR  71646 . This is an “open house” meeting with no formal presentations.

The design plans and EA are available online and in-person for public review and comment from Tuesday, May 28, until 4:30 p.m. Friday, July 12, in the following locations:

  • Website: www.ardot.gov/publicmeetings
  • ARDOT’s Area Maintenance Office in Hamburg: 1257 Highway 82 East, Hamburg, AR 71646
  • ARDOT’s District 2 Office in Pune Bluff: 4900 Highway 65 South, Pine Bluff, AR 71611

Link to Meeting Materials

(Please note that this link will not be active until May 28 )

A Spanish translation of the presentation is available on the website. Submit online comment forms at https://arcg.is/5K999 or print the form and mail to Environmental Division, P.O. Box 2261, Little Rock, AR 72203-2261.  If you do not have internet access, please contact Ruby Jordan-Johnson at (501)-569-2379 or email [email protected] to ask questions about the proposed project.

Anyone needing project information or special accommodations under the Americans with Disabilities Act (ADA) is encouraged to write to Ruby Jordan-Johnson, P.O. Box 2261, Little Rock, AR 72203-2261, call (501)569-2379,fax (501)569-2009 or email [email protected].  Hearing or speech impaired, please contact the Arkansas Relay System at (Voice/TTY 711).  Requests should be made at least four days prior to the public meeting.

Hearing or speech impaired, please contact the Arkansas Relay System at (Voice/TTY 711).

The Arkansas Department of Transportation (ARDOT) complies with all civil rights provisions of federal statutes and related authorities that prohibit discrimination in programs and activities receiving federal financial assistance. Therefore, ARDOT does not discriminate on the basis of race, sex, color, age, national origin, religion (not applicable as a protected group under the Federal Motor Carrier Safety Administration Title VI Program), disability, Limited English Proficiency (LEP), or low-income status in the admission, access to and treatment in ARDOT’s programs and activities, as well as ARDOT’s hiring or employment practices. Complaints of alleged discrimination and inquiries regarding ARDOT’s nondiscrimination policies may be directed to Civil Rights Officer Joanna P. McFadden (ADA/504/Title VI Coordinator), PO Box 2261, Little Rock, Arkansas 72203-2261, 501-569-2298 (Voice/TTY 711), or to the following email address: [email protected] .  

Free language assistance for Limited English Proficient individuals is available upon request.

This notice is available from the ADA/504/Title VI Coordinator in large print, on audiotape and in Braille.

Contact: Ellen Coulter

May 28, 2024

Follow ARDOT

Bridgeport Fire Department talks about storms that hit Harrison County

During the Memorial Day weekend, people had a lot of fun, but there was also a lot of rain.

BRIDGEPORT, W.Va (WDTV) -During the Memorial Day weekend, people had a lot of fun, but there was also a lot of rain.

Over the weekend, storms rolled through Hudson County, dumping approximately 3 to 3.5 inches of rain. The Bridgeport Fire Department says the fast-moving water created problems for them and the public.

“The department was pretty busy all through the weekend with consequences from the storm, which had a lot of houses with significant water get up into them—some people stranded in campers, in their homes and vehicles. Saturday or Sunday night, it was pretty much a sleepless night,” said Ben Tacy, lieutenant training officer, Bridgeport Fire Department

The Bridgeport fire department responded to over 22 emergency calls during the storms, which is double its average.

Copyright 2024 WDTV. All rights reserved.

Ruby Memorial Hospital is the largest hospital in the WVU Medicine network.

Main steam line breaks at Ruby Memorial Hospital

Flooding in NCWV

A look at Saturday night’s flooding in NCWV

WVU Selected to NCCA Baseball Tournament

WVU Baseball Heading To Tucson, Arizona For NCAA College Baseball Tournament

Flooding in North Central West Virginia

Officials urge Harrison County residents to fill out survey regarding storm damage

A rockslide closes Route 250 in Marion County.

UPDATE: Route 250 in Marion County reopen after rockslide

Latest news.

assignment statements in ruby

Khegan McLane on Tunesday! Performance

assignment statements in ruby

Khegan McLane on Tunesday!

assignment statements in ruby

New Pizzeria

assignment statements in ruby

Bonnie's Bus & LUCAS

assignment statements in ruby

Locker Shields

IMAGES

  1. Assignment Operators in Ruby

    assignment statements in ruby

  2. PPT

    assignment statements in ruby

  3. If Statements

    assignment statements in ruby

  4. Ruby Assignment Operator Example

    assignment statements in ruby

  5. Decision Making in Ruby (if else)

    assignment statements in ruby

  6. Ruby tutorial

    assignment statements in ruby

VIDEO

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

  2. SDT for Assignment Statements

  3. Hunter assignment Ruby game boys double attitude

  4. Ruby Todman KPB117 2024 n11224258

  5. Hunter assignment Ruby game boys attitude

  6. Expressions and Assignment Statements

COMMENTS

  1. 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.

  2. 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).

  3. The Beginners Guide to Ruby If & Else Statements

    If something is true (the condition) then you can do something. In Ruby, you do this using if statements: stock = 10. if stock < 1. puts "Sorry we are out of stock!" end. Notice the syntax. It's important to get it right. The stock < 1 part is what we call a "condition".

  4. Programming Ruby: The Pragmatic Programmer's Guide

    An assignment statement sets the variable or attribute on its left side (the lvalue) to refer to the value on the right (the rvalue). It then returns that value as the result of the assignment expression. ... As of Ruby 1.6.2, if an assignment has one lvalue and multiple rvalues, the rvalues are converted to an array and assigned to the lvalue.

  5. Ruby Case Statements (Full Tutorial With Examples)

    Ruby Case & Ranges. The case statement is more flexible than it might appear at first sight. Let's see an example where we want to print some message depending on what range a value falls in. case capacity. when 0. "You ran out of gas." when 1..20. "The tank is almost empty. Quickly, find a gas station!"

  6. 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:

  7. control_expressions

    Control Expressions. Ruby has a variety of ways to control execution. All the expressions described here return a value. For the tests in these control expressions, nil and false are false-values and true and any other object are true-values. In this document "true" will mean "true-value" and "false" will mean "false-value".

  8. Introduction to Ruby

    Ruby has a notion of true and false. This is best illustrated through some example. Start irb and type the following: The if statements evaluates whether the expression (e.g. 'city == "Toronto") is true or false and acts accordingly. Warning: Notice the difference between '=' and '=='. '=' is an assignment operator. '==' is a comparison ...

  9. Assignments

    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:. o.m = v The Ruby interpreter converts this assignment to the following method invocation:

  10. How do I use the conditional operator (? :) in Ruby?

    1. Be careful blindly chopping off a line at a given column. You can end up cutting a word midway then appending the elipsis ('...'), which looks bad. Instead, look for a nearby punctuation or whitespace character, and truncate there. Only if there is no better breaking point nearby should you truncate mid-word.

  11. 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 need to perform more complex logic based on a conditional or allow for > 2 outcomes, if/elsif/else statements ...

  12. Official Ruby FAQ

    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. Note that the assignment does not have to be executed—Ruby just has to have ...

  13. Difference between "or" and || in Ruby?

    It's a matter of operator precedence. || has a higher precedence than or. So, in between the two you have other operators including ternary (? :) and assignment (=) so which one you choose can affect the outcome of statements.Here's a ruby operator precedence table.. See this question for another example using and/&&.. Also, be aware of some nasty things that could happen:

  14. if statement

    Since Ruby parses the bare a left of the if first and has not yet seen an assignment to a it assumes you wish to call a method. Ruby then sees the assignment to a and will assume you are referencing a local method. The confusion comes from the out-of-order execution of the expression. First the local variable is assigned-to then you attempt to ...

  15. Conditional Statements in Ruby

    If Statements. The most basic form of a conditional statement is the if statement. It allows us to execute a block of code only if a certain condition is met. Here is a simple example: age = 25. if age > 18. puts "You are an adult!" end. In this example, we first declare a variable age with a value of 25.

  16. 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 ...

  17. Ruby

    A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Similarly, in Ruby, the if-else statement is used to test the specified condition.

  18. Statements vs Expressions in Ruby

    In Ruby, sometimes statements can also be expressions under certain conditions, for example: assignment statement. In a = a = b, the first assignment a = b is an expression and returns value of b.

  19. How to Use The Ruby Ternary Operator (?:)

    That's part of the syntax! It's how Ruby knows that you're writing a ternary operator. Next: We have whatever code you want to run if the condition turns out to be true, the first possible outcome. Then a colon (: ), another syntax element. Lastly, we have the code you want to run if the condition is false, the second possible outcome.

  20. Ruby Programming

    Ruby was named after the precious gem.. Ruby is an interpreted, object-oriented programming language. Its creator, Yukihiro Matsumoto, aka "Matz", released it to the public in 1995.Its history is covered here.Its many features are listed here.. The book is currently broken down into several sections and is intended to be read sequentially.

  21. How to define a method for a block in Ruby?

    How to write a switch statement in Ruby. 1530 How to check if a value exists in an array in Ruby. 1266 How to call shell commands from Ruby. 1154 What is attr_accessor in Ruby? 1212 How to understand nil vs. empty vs. blank in Ruby. 1051 ...

  22. 2.10: Assignment and Equality

    Another difference between assignment and equality is that a mathematical equality is true (or false) for all eternity; an assignment statement is temporary. When you assign x = y + 1, you get the current value of y. If y changes later, x does not get updated. A third difference is that a mathematical equality is a statement that may or may not ...

  23. Giuliani agrees to stop spreading 2020 vote-tampering lies about ...

    The Assignment with Audie Cornish ... Ruby Freeman and her daughter, Shaye Moss. ... and/or assisting in others' publication of any statements that suggest that Plaintiffs, whether mentioned ...

  24. 1.6.1: More About Valid Variable Names

    1.6: Variables and Assignment Statements; 1.7: Clearing the Workspace, Readability Tips; Was this article helpful? Yes; No; Recommended articles. Article type Section or Page Author Carey Smith Autonumber Section Headings title with colon delimiters License CC BY-NC-SA License Version 4.0 Show TOC yes; Tags.

  25. Python (programming language)

    Python is a high-level, general-purpose programming language.Its design philosophy emphasizes code readability with the use of significant indentation.. Python is dynamically typed and garbage-collected.It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming.It is often described as a "batteries included" language ...

  26. 'We can't continue': Entire preschool staff resigns at once

    The entire staff at a preschool in Ohio resigned due to what they call a lack of transparency surrounding the budget.

  27. ARDOT to Host Location and Design Public Hearing for Proposed Widening

    Anyone needing project information or special accommodations under the Americans with Disabilities Act (ADA) is encouraged to write to Ruby Jordan-Johnson, P.O. Box 2261, Little Rock, AR 72203-2261, call (501)569-2379,fax (501)569-2009 or email [email protected]. Hearing or speech impaired, please contact the Arkansas Relay ...

  28. Jack Ruby

    Jack Leon Ruby (born Jacob Leon Rubenstein; c. March 25, 1911 - January 3, 1967) was an American nightclub owner who murdered Lee Harvey Oswald on November 24, 1963, two days after Oswald was accused of the assassination of President John F. Kennedy.Ruby shot and mortally wounded Oswald on live television in the basement of Dallas Police Headquarters and was immediately arrested.

  29. Bridgeport Fire Department talks about storms that hit Harrison ...

    BRIDGEPORT, W.Va (WDTV) -During the Memorial Day weekend, people had a lot of fun, but there was also a lot of rain. Over the weekend, storms rolled through Hudson County, dumping approximately 3 ...