Ruby Case Statement Assignment Sheet

Arrays

An array is a Ruby data type that holds an ordered collection of values, which can be any type of object including other arrays.

Creating arrays

Ruby arrays can be created with either literal notation or the constructor.

Syntax

Example

Syntax

Example

Syntax

Example

Read more

Array.each

You can iterate over the elements in an array using , which takes a block.

Syntax

Example

Read more

Array.flatten

returns a one-dimensional version of a multi-dimensional array. It does not overwrite the array with the new array.

Example

Read more

Array.uniq

You can remove duplicates from an array using .

Example

Read more

Blocks

A block is a chunk of code that lives inside a control statement, loop, method definition, or method call. It returns the value of its last line. In Ruby, blocks can be created two ways: with braces or with a do/end statement.

Syntax

Example

Syntax

Example

Booleans

In Ruby, there are two boolean values: and .

Syntax

Logical Operators

Logical operators are used to compare to boolean values. Ruby has 6 operators to compare boolean values: , , , , , and . and , and , and and have the same functionality but the verbiage operators (, and ) have lower precedence than the symbolic operators (, and ).

Syntax

Example

Read more

Comparison Operators

Comparison operators are used to test the relationship between two objects. The equality () and inequality () operators can be used on almost any type of value where the other operators are used for numeric comparisons.

Syntax

Example

Adding human-readable comments to your programs is a good idea to help others who read your code understand what it does. However in Ruby, it is common to not write many comments, since the language is so human-readable already. It's usually very easy to quickly understand what a good piece of Ruby code does.

Single-line

Single line comments are great for quick notes, reminders, or sharing trivial information.

Syntax

Example

Multi-line

You can span a comment multiple lines, although Ruby programmers rarely use this. They are useful when making notes for documentation.

Syntax

Example

Hashes

Hashes are collections of key-value pairs. Like arrays, they have values associated with indices, but in the case of hashes, the indices are called "keys." Keys can be anything that's hashable, such as integers, strings, or symbols, but they must be unique for the hash they belong. The values to which keys refer can be any Ruby object.

Creating Standard Hashes

There are several ways to create hashes in Ruby. The common most two are the new constructor method and its literal notation. It is also considered a best practice to use symbols as keys. The following are valid in all versions of Ruby.

Syntax

Example

Syntax

Example

Creating Shorthand Hashes

As of Ruby 1.9, there is now a shorthand method for writing hashes that's a lot easier to write. Rather than specifying a symbol then using the hash rockets to define key value pairs, you can now just put the key followed by a colon then the value. The keys get translated into symbols.

Syntax

Example

if, unless, elsif and else

if

Ruby includes an if statement that can be used to manage a program's control flow. The statement takes a boolean expression and executes certain code only if the boolean expression evaluates to true.

Syntax

Example

unless

This is the opposite of an if statement. The statement takes a boolean expression and executes certain code only if the boolean expression evaluates to false.

Syntax

Example

elsif

A conditional statement used to manage a program's control flow. The statement must be paired with an if or unless block and takes a boolean expression. It runs certain code only if the previous conditional statements do not run and its boolean expression evaluates to true. it is equivalent to writing an else statement that has an if statement in its block.

Syntax

Example

else

A conditional statement used to manage a program's control flow. The statement must be paired with an if or unless block and takes no arguments. It runs certain code only if the previous conditional statements do not run.

Syntax

Example

Loops

While Loops

Ruby includes a while loop that will execute a block of code as long as its condition is true. When the condition becomes false, the code after the end of the loop will be executed.

Syntax

Example

Until Loops

Ruby includes an until loop that will execute a block of code as long as its condition is false. When the condition becomes true, the code after the end of the loop will be executed.

Syntax

Example

For Loops

The for loop is used to iterate an object. The Ruby .each method is preferred over the for loop because the for loop does not create a new scope for the object whereas the .each method does. The for loop is rare in Ruby.

Syntax

Example

Example

Math

Basic Arithmetic

Your typical addition, subtraction, multiplication, division, and exponentiation all exist in Ruby and look very similar to your typical use cases in algebra. Note that order of operations holds.

Syntax

Example

Division

Division is a tricky situation. If you divide two integers, the outcome will be an integer regardless of remainder (see modulus below for more information). However, if you divide an integer with a floating point number or two floating point numbers, the outcome will account for the remainder.

Example

.divmod

If you want to do integer division and retrieve both the quotient and the remainder in one call, then you want to use divmod. You can use divmod on a numeric type and it will return an array with the quotient and the remainder, respectively.

Syntax

Example

Modulus Division

If you would like the remainder from an integer division problem, you would use the modulus operator to retrieve the value.

Syntax

Example

.floor

Returns the largest integer less than or equal to a number.

Syntax

Example

.ceil

Returns the smallest integer greater than or equal to a number.

Syntax

Example

PI

Returns the ratio of the circumference of a circle to its diameter, approximately 3.14159 or in better terms, the value of PI (π). Note in syntax , we do not put at the end of because is not a function but rather a constant.

Syntax

.sqrt

Returns the square root of a number.

Syntax

Example

Methods

A Ruby method is used to create parameterized, reusable code. Ruby methods can be created using the syntax:

Syntax

Example

puts vs. print

The puts (short for "put string") and print commands are both used to display the results of evaluating Ruby code. The primary difference between them is that puts adds a newline after executing, and print does not.

Syntax

Example

Strings

Strings are used for storing and manipulating text in Ruby. Strings are written between quotation marks. Both single (') and double (") quotes are supported, but quotes at each end of a single string must match (no "strings' or 'strings")!

Syntax

Example

Switch statement

Acts like a big if / else if / else chain. Checks a value against a list of cases, and executes the first case that is true. If it does not find a match, it attempts the default case designated by an else statement. If there is not a default case, then it exits the statement. Unlike languages like JavaScript, Ruby switch statements have no fall through and automatically break. Instead, cases can be comma delimited.

Syntax

Example

Symbols

In Ruby, a symbol is simply a name used in your program. One of the main uses for Ruby symbols is hash keys, especially if you would otherwise use the same string as a hash key over and over. Ruby will create an (almost) unlimited number of string instances for all your hash keys, but will only keep one copy of a symbol in memory at a time. This can really save memory for your programs in the long run.

Syntax

Example

Ternary Operator

This is a shorthand statement for a simple if...else statement. It is a useful tool in situations where you have an extremely simple if...else statement where you are trying to assign a value to a variable.

Syntax

Example

times and each Methods

.each

.each is a built in iterator function in Ruby. It loops through each item in a list, hash, or other iterable object allowing you to perform operations on that value. The block of an .each statement creates a new scope for your variable so you don't accidentally modify the original value.

Syntax

Example

.times

.times is a built in iterator function in Ruby. It performs an action a given number of times.

Syntax

Example

Variables

Variables are assigned values using the = operator, which is not to be confused with the == sign used for testing equality. A variable can hold almost any type of value including numbers, strings, arrays, and hashes.

Assignment

Syntax

Example

Changing/Reassignment

Syntax

Example

Whenever you need to use some statements you could consider using a Ruby case statement instead. In this post, you will learn a few different use cases and how it all really works under the hood.

Note: In other programming languages this is known as a switch statement.

The components of a case statement in Ruby:

KeywordDescription
caseStarts a case statement definition. Takes the variable you are going to work with.
whenEvery condition that can be matched is one when statement.
elseIf nothing matches then do this. Optional.

Ruby Case & Ranges

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

I think this code is pretty elegant compared to what the version would look like.

Ruby Case & Regex

You can also use regular expressions as your condition. In the following example we have a with an initial letter that tells us how risky this product is to consume.

When Not to Use Ruby Case

When you have a simple 1:1 mapping, you might be tempted to do something like this.

In my opinion it would be better to do this instead:

The hash solution is more efficient and easier to work with. Don’t you think?

How case works: the === method

You may be wondering how works under the hood. If we go back to our first example, this is what is happening:

As you can see, the condition is reversed because Ruby calls on the object on the left. The is just a method that can be implemented by any class. In this case, implements this method by returning true only if the value is found inside the range.

This is how is implemented in Rubinius (for the class):

Source: https://github.com/rubinius/rubinius/blob/master/core/range.rb#L178

Procs + Case

Another interesting class that implements is the class.

Related post: Learn more about procs & lambdas.

In this example I define two , one to check for an number, and another for .

This is what is really happening:

Using on a proc has the same effect as using .

Conclusion

You have learned how the Ruby case statement works and how flexible it can be. Now it’s your turn to start making the best use of it in your own projects.

I hope you found this article useful!

Please share this post so more people can learn! 🙂

Related

Share this post!

casecapacity

when0

  "You ran out of gas."

when1..20

  "The tank is almost empty. Quickly, find a gas station!"

when21..70

  "You should be ok for now."

when71..100

  "The tank is almost full."

else

  "Error: capacity has an invalid value (#{capacity})"

end

caseserial_code

when/\AC/

  "Low risk"

when/\AL/

  "Medium risk"

when/\AX/

  "High risk"

else

  "Unknown risk"

end

casecountry

when"europe"

  "http://eu.example.com"

when"america"

  "http://us.example.com"

end

SITES={

  "europe"  =>"http://eu.example.com",

  "america"=>"http://us.example.com"

}

 

SITES[country]

(1..20)   ===capacity

(21..70)  ===capacity

(71..100)===capacity

def===(value)

  include?(value)

end

odd  =proc(&:odd?)

even=proc(&:even?)

 

casenumber

whenodd

  puts"Odd number"

wheneven

  puts"Even number"

end

odd.===(number)

even.===(number)

One thought on “Ruby Case Statement Assignment Sheet

Leave a Reply

Your email address will not be published. Required fields are marked *