• 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

The case statement is a multiway branch statement just like a switch statement in other languages. It provides an easy way to forward execution to different parts of code based on the value of the expression.

There are 3 important keywords which are used in the case statement:

  • case : It is similar to the switch keyword in another programming languages. It takes the variables that will be used by when keyword.
  • when : It is similar to the case keyword in another programming languages. It is used to match a single condition. There can be multiple when statements into a single case statement.
  • else : It is similar to the default keyword in another programming languages. It is optional and will execute when nothing matches.

Flow Chart:

ruby case statement assignment

Important Points:

Please Login to comment...

Similar reads.

author

  • Ruby-Basics

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

+123-456-7890

[email protected]

Mon - Fri: 7AM - 7PM

Conference on optimizing Ruby code execution

An In-depth Guide to Master the Ruby Case Statement

In Ruby, case statements serve as a robust substitute for a series of if/elsif conditions, streamlining the decision-making process within your code. This article elucidates various scenarios where case statements prove particularly beneficial and delves into the mechanics of their operation.

Structure of a Ruby Case Statement

A Ruby case statement is structured around several key components:

  • case : Initiates the case statement, evaluating the variable in question;
  • when : Represents individual conditions to be matched;
  • else : Executes an alternative action if no conditions match, though this is optional.

Utilizing Case Statements with Ranges

Case statements exhibit remarkable flexibility, as demonstrated in scenarios requiring action based on a variable’s range. For instance, assessing a ‘capacity’ value to determine fuel status can be elegantly handled with a case statement:

Implementing Regex Conditions

Case statements also accommodate regular expressions for conditions, allowing for sophisticated pattern matching. For example, evaluating a ‘serial_code’ to gauge product risk levels:

When to Opt for Alternatives to Case Statements

For straightforward 1:1 mappings, such as assigning URLs based on a ‘country’ variable, utilizing a hash map might offer a more efficient solution than a case statement:

Insight into the === Method

The essence of case statement functionality in Ruby is the === method, which is invoked on the left-side object, enabling flexible and diverse condition checks, including range inclusion.

The Efficacy of Procs in Case Statements

The Proc class, implementing the === method, extends the versatility of case statements. This enables dynamic condition evaluations, such as distinguishing between even and odd numbers:

Comparative Table

Through exploring the capabilities and applications of Ruby case statements, it’s clear they offer a powerful tool for enhancing code readability and efficiency. Embracing case statements in your Ruby projects can simplify complex conditional logic, paving the way for clearer and more maintainable code.

Recommended Articles

Programming code

Ruby’s Substring Extraction: A Comprehensive Guide

Install Gems from Gemfile in Ruby

Ruby Gems & Bundler: Code Mastery

The laptop stands in front of a background of colored cubes

Ruby Sets: An Efficient Approach to Data Management

Leave a comment cancel reply.

You must be logged in to post a comment.

Ruby's case statement - advanced techniques

Nothing could be simpler and more boring than the case statement. It’s a holdover from C. You use it to replace a bunch of ifs. Case closed. Or is it? Actually, case statements in Ruby are a lot richer and more complex than you might imagine. Let’s take a look.

author photo

  • Jul 15, 2015

Nothing could be simpler and more boring than the case statement. It's a holdover from C. You use it to replace a bunch of ifs. Case closed. Or is it?

Actually, case statements in Ruby are a lot richer and more complex than you might imagine. Let's take a look at just one example:

This example shows that case statements not only match an item's  value but also its  class . This is possible because under the hood, Ruby uses the === operator, aka. the three equals operator.

A quick tour of the === operator

When you write x === y y in Ruby, you're asking "does y belong in the group represented by x?" This is a very general statement. The specifics vary, depending on the kind of group you're working with.

Strings, regular expressions and ranges all define their own ===(item) methods, which behave more or less like you'd expect.  You can even add a triple equals method to your own classes.

Now that we know this, we can do all sorts of tricks with case.

Matching ranges in case statements

You can use ranges in case statements thanks to the fact that range === n simply returns the value of range.include?(n) . How can I be so sure? It's in the docs .

Matching regular expressions with case statements

Using regexes in  case statements is also possible, because /regexp/ === "string" returns true only if the string matches the regular expression. The docs for Regexp explain this.

Matching procs and lambdas

This is kind of a weird one. When you use   Proc#===(item) , it's the same as doing Proc#call(item) . Here are the docs  for it. What this means is that you can use lambdas and procs in your case statement as dynamic matchers.

Writing your own matcher classes

As I mentioned above, adding custom case behavior to your classes is as simple as defining your own === method. One use for this might be to pull out complex conditional logic into multiple small classes. I've sketched out how that might work in the example below:

  • Try Honeybadger for FREE Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list. Start free trial Easy 5-minute setup — No credit card required
  • Get the Honeybadger newsletter Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you. Sign up Include latest Ruby articles

Starr Horne

Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.

  • @starrhorne Author Twitter

More Ruby articles

  • Apr 23, 2024 Shipping Rails logs with Kamal and Vector
  • Apr 09, 2024 Account-based subdomains in Rails
  • Mar 12, 2024 Let's build a Hanami app
  • Mar 05, 2024 How to deploy a Rails app to Render
  • Feb 12, 2024 Visualizing Ahoy analytics in Rails
  • Feb 07, 2024 Building reusable UI components in Rails with ViewComponent
  • Jan 17, 2024 Composite primary keys in Rails
  • Dec 14, 2023 Deploy a Rails app to a VPS with Kamal
  • Nov 20, 2023 How to build your own user authentication system in Rails
  • Nov 02, 2023 How to organize your code using Rails Concerns

Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

  • Know when critical errors occur, and which customers are affected.
  • Respond instantly when your systems go down.
  • Improve the health of your systems over time.
  • Fix problems before your customers can report them!

As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

ruby case statement assignment

Honeybadger is trusted by top companies like:

ruby case statement assignment

Get Honeybadger's best Ruby articles in your inbox

We publish 1-2 times per month. Subscribe to get our Ruby articles as soon as we publish them.

We're Honeybadger. We'll never send you spam; we will send you cool stuff like exclusive content, memes, and swag.

How A Ruby Case Statement Works And What You Can Do With It

Table of contents.

ruby print "Enter your grade: " grade = gets.chomp case grade when "A" puts 'Well done!' when "B" puts 'Try harder!' when "C" puts 'You need help!!!' else puts "You just making it up!" end

So far nothing special, the above works just the way you would expect. But, you can do more with a case statement in Ruby.

Multi-Value When And No-Value Case

Ruby allows you to supply multiple values to a when statement rather than just one e.g.:

ruby print "Enter your grade: " grade = gets.chomp case grade when "A", "B" puts 'You pretty smart!' when "C", "D" puts 'You pretty dumb!!' else puts "You can't even use a computer!" end

Pretty cool, but nothing too revolutionary. It doesn’t end there though you can use a case statement without giving it a value to match against, which allows a case statement to mimic the behavior of an if statement, e.g.:

ruby print "Enter a string: " some_string = gets.chomp case when some_string.match(/\d/) puts 'String has numbers' when some_string.match(/[a-zA-Z]/) puts 'String has letters' else puts 'String has no numbers or letters' end

So, why would you use it instead of an if statement? Well, there is probably no reason, they are equivalent. But, it is good to be aware that you can do this, especially if you run into it in the wild, wouldn’t want to be caught unawares.

It All Evaluates To An Object

You probably keep hearing this over and over, but everything in Ruby works with objects. Things are no different when it comes to case statements. A case statement will always return a single object, just like a method call. So, you can safely wrap a case statement in a method call and Ruby will have no problems with it. For example, the above version of the case statement ca be re-written like this:

ruby print "Enter a string: " some_string = gets.chomp puts case when some_string.match(/\d/) 'String has numbers' when some_string.match(/[a-zA-Z]/) 'String has letters' else 'String has no numbers or letters' end

We are now wrapping the whole case statement in a puts method call, rather than doing it within each individual when statement. This works because no matter which when/else succeeds, the whole case statement returns the result of the last line that was executed (in our case it just always returns a string), and so the puts just writes out whatever string is returned.

How It All Works Under The Hood

You can almost consider case/when statements to be syntactic sugar for a method call. Every object in Ruby inherits a method called the case equality method, also known as the triple equals (===). You can think of it as an operator if it helps (the === operator), but we know that Ruby operators are just syntactic sugar for method calls. So whenever a when is trying to match a value (except when we are using a no-value case ) there is a method call behind the scenes to the === method/operator. We can therefore take our very first example and re-write it using if statements to be completely equivalent to a case statement:

ruby print "Enter your grade: " grade = gets.chomp if "A" === grade puts 'Well done!' elsif "B" === grade puts 'Try harder!' elsif "C" === grade puts 'You need help!!!' else puts "You just making it up!" end

The implications of this are as follows. Any class you write can override the === method and therefore define it’s own behavior for usage in a case statement. For built-in objects such as strings, the === operator/method is simply equivalent to the == method/operator. But you don’t have to be restricted to this. If you want your class to have the ability to participate in a case statement in some specialized way all you need to do is something like this:

```ruby class Vehicle attr_accessor :number_of_wheels

def initialize(number_of_wheels) @number_of_wheels = number_of_wheels end

def ===(another_vehicle) self.number_of_wheels == another_vehicle.number_of_wheels end end

four_wheeler = Vehicle.new 4 two_wheeler = Vehicle.new 2

print “Enter number of wheel for vehicle: “ vehicle = Vehicle.new gets.chomp.to_i

puts case vehicle when two_wheeler ‘Vehicle has the same number of wheels as a two-wheeler!’ when four_wheeler ‘Vehicle has the same number of wheels as a four-wheeler!’ else “Don’t know of a vehicle with that wheel arrangement!” end```

In this case even though we are matching directly on the vehicle object in our case/when statement, behind the scenes a method call is made to the === operator and so the real match is made on the number of wheels attribute that the vehicle object has (as per what is defined in the === method).

This idea of hiding method calls behind syntax that doesn’t look like method calls, seems to be rather common in Ruby. Personally I like it, you can do some rather elegant things, but the building blocks are still just a bunch of method calls. When it comes to the case statement though, I hardly ever use it when I program in Java for example, but it looks to me like it can be somewhat more handy in Ruby especially with the ability to define custom case behavior for your own objects.

Image by dahliascakes

ruby case statement assignment

How do I use ‘case’ statements in Ruby?

In Ruby, the `case` statement, also known as a switch statement in other programming languages, is used to evaluate a value against a series of possible conditions and execute code based on the first matching condition. It provides a clean and efficient way to handle multiple branches of conditional logic. Here’s how to use the `case` statement in Ruby:

  • Basic `case` Statement: The basic structure of a `case` statement consists of the `case` keyword, followed by the expression you want to evaluate (usually a variable), and then a series of `when` clauses that specify possible conditions. Each `when` clause contains a condition to match against the expression and a block of code to execute if the condition is true. The `else` clause is optional and serves as a fallback for when none of the conditions match.

In this example, the `case` statement evaluates the value of `grade` and executes the code block associated with the first matching condition, which is `’B’`. It will output “Good job!”

  • Using Ranges: You can use ranges in `when` clauses to match values within a specific range. This is particularly useful for evaluating numeric or character ranges.

 In this example, the `case` statement uses ranges to determine the grade based on the `score`.

  • Using `then` for One-Liners: You can use `then` to write one-liner code for `when` clauses when the code is short and concise.

The `case` statement in Ruby provides a clean and organized way to handle multiple conditions, making your code more readable and maintainable. It’s especially useful when you have a value to compare against several possible options. The `case` statement evaluates conditions sequentially and executes the first matching block of code, offering a versatile tool for branching logic in your Ruby programs.

ruby case statement assignment

Ruby Guides

Hire ruby developers peru, hire ruby developers uruguay, hire ruby developers chile.

Using the Case (Switch) Ruby Statement

GrapchicStock / Getty Images

  • Ruby Programming
  • PHP Programming
  • Java Programming
  • Javascript Programming
  • Delphi Programming
  • C & C++ Programming
  • Visual Basic

In most computer languages , the case or conditional (also known as  switch ) statement compares the value of a variable with that of several constants or literals and executes the first path with a matching case. In Ruby , it's a bit more flexible (and powerful).

Instead of a simple equality test being performed, the case equality operator is used, opening the door to many new uses.

There are some differences from other languages though. In C , a switch statement is a kind of replacement for a series of if and goto statements. The cases are technically labels, and the switch statement will go to the matching label. This exhibits a behavior called "fallthrough," as the execution doesn't stop when it reaches another label.

This is usually avoided using a break statement, but fallthrough is sometimes intentional. The case statement in Ruby, on the other hand, can be seen as a shorthand for a series of if statements. There is no fallthrough, only the first matching case will be executed.

The Basic Form of a Case Statement

The basic form of a case statement is as follows.

As you can see, this is structured something like an if/else if/else conditional statement. The name (which we'll call the value ), in this case inputted from the keyboard, is compared to each of the cases from the when clauses (i.e.  cases ), and the first when block with a matching case will be executed. If none of them match, the else block will be executed.

What's interesting here is how the value is compared to each of the cases. As mentioned above, in C++ , and other C-like languages, a simple value comparison is used. In Ruby, the case equality operator is used.

Remember that the type of the left-hand side of a case equality operator is important, and the cases are always the left-hand side. So, for each when clause, Ruby will evaluate case === value until it finds a match.

If we were to input Bob , Ruby would first evaluate "Alice" === "Bob" , which would be false since String#=== is defined as the comparison of the strings. Next, /[qrz].+/i === "Bob" would be executed, which is false since Bob doesn't begin with Q, R or Z.

Since none of the cases matched, Ruby will then execute the else clause.

How the Type Comes Into Play

A common use of the case statement is to determine the type of value and do something different depending on its type. Though this breaks Ruby's customary duck typing, it's sometimes necessary to get things done.

This works by using the Class#=== (technically, the Module#=== ) operator, which tests if the right-hand side is_a? left-hand side.

The syntax is simple and elegant:

Another Possible Form

If the value is omitted, the case statement works a bit differently: it works almost exactly like an if/else if/else statement. The advantages of using the case statement over an ​ if statement, in this case, are merely cosmetic.

A More Compact Syntax

There are times when there are a large number of small when clauses. Such a case statement easily grows too large to fit on the screen. When this is the case (no pun intended), you can use the then keyword to put the body of the when clause on the same line.

While this makes for some very dense code, as long as each when clause is very similar, it actually becomes more readable.

When you should use single-line and multi-line when clauses are up to you, it's a matter of style. However, mixing the two is not recommended - a case statement should follow a pattern to be as readable as possible.

Case Assignment

Like if statements, case statements evaluate to the last statement in the when clause. In other words, they can be used in assignments to provide a kind of table. However, don't forget that case statements are much more powerful than simple array or hash lookups. Such a table doesn't necessarily need to use literals in the when clauses.

If there is no matching when clause and no else clause, then the case statement will evaluate to nil .

  • Using the Switch Statement for Multiple Choices in Java
  • The 7 Best Programming Languages to Learn for Beginners
  • Conditional Statements in Java
  • String Literals
  • If-Then and If-Then-Else Conditional Statements in Java
  • What Are Ternary (Conditional) Operators in Ruby?
  • How to Use Loops in Ruby
  • The JavaScript Ternary Operator as a Shortcut for If/Else Statements
  • How to Use String Substitution in Ruby
  • Control Statements in C++
  • Basic Guide to Creating Arrays in Ruby
  • Using the Command Line to Run Ruby Scripts
  • Using the Each Method in Ruby
  • Global Variables in Ruby
  • Using the "Split" Method
  • Java Expressions Introduced

Ruby Language

  • Getting started with Ruby Language
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • Blocks and Procs and Lambdas
  • C Extensions
  • Casting (type conversion)
  • Catching Exceptions with Begin / Rescue
  • Command Line Apps
  • Control Flow
  • Case statement
  • Control flow with logic statements
  • Flip-Flop operator
  • if, elsif, else and end
  • Inline if/unless
  • Loop control with break, next, and redo
  • Or-Equals/Conditional assignment operator (||=)
  • return vs. next: non-local return in a block
  • Ternary operator
  • throw, catch
  • Truthy and Falsy values
  • while, until
  • Design Patterns and Idioms in Ruby
  • Destructuring
  • Dynamic Evaluation
  • Enumerable in Ruby
  • Enumerators
  • Environment Variables
  • File and I/O Operations
  • Gem Creation/Management
  • Generate a random number
  • Getting started with Hanami
  • Implicit Receivers and Understanding Self
  • Inheritance
  • Installation
  • instance_eval
  • Introspection
  • Introspection in Ruby
  • JSON with Ruby
  • Keyword Arguments
  • Loading Source Files
  • Message Passing
  • Metaprogramming
  • method_missing
  • Monkey Patching in Ruby
  • Multidimensional Arrays
  • Operating System or Shell commands
  • OptionParser
  • Pure RSpec JSON API testing
  • Recursion in Ruby
  • Refinements
  • Regular Expressions and Regex Based Operations
  • Ruby Access Modifiers
  • Ruby Version Manager
  • Singleton Class
  • Special Constants in Ruby
  • Splat operator (*)
  • Variable Scope and Visibility

Ruby Language Control Flow Case statement

Fastest entity framework extensions.

Ruby uses the case keyword for switch statements.

As per the Ruby Docs :

Case statements consist of an optional condition, which is in the position of an argument to case , and zero or more when clauses. The first when clause to match the condition (or to evaluate to Boolean truth, if the condition is null) “wins”, and its code stanza is executed. The value of the case statement is the value of the successful when clause, or nil if there is no such clause. A case statement can end with an else clause. Each when a statement can have multiple candidate values, separated by commas.

Shorter version:

The value of the case clause is matched with each when clause using the === method (not == ). Therefore it can be used with a variety of different types of objects.

A case statement can be used with Ranges :

A case statement can be used with a Regexp :

A case statement can be used with a Proc or lambda:

A case statement can be used with Classes :

By implementing the === method you can create your own match classes:

A case statement can be used without a value to match against:

A case statement has a value, so you can use it as a method argument or in an assignment:

Got any Ruby Language Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

An Array of Possibilities: A Guide to Ruby Pattern Matching

Pattern matching is a powerful tool commonly found in functional programming languages. The Ruby 2.7 release is going to include this feature.

In this article, Toptal Ruby Developer Noppakun Wongsrinoppakun provides a breakdown of what this addition will include and why it matters.

An Array of Possibilities: A Guide to Ruby Pattern Matching

By Noppakun Wongsrinoppakun

Noppakun is a Tokyo-based full-stack software engineer with extensive experience using Vue.js and Ruby on Rails.

Pattern matching is the big new feature coming to Ruby 2.7. It has been committed to the trunk so anyone who is interested can install Ruby 2.7.0-dev and check it out. Please bear in mind that none of these are finalized and the dev team is looking for feedback so if you have any, you can let the committers know before the feature is actually out.

I hope you will understand what pattern matching is and how to use it in Ruby after reading this article.

What Is Pattern Matching?

Pattern matching is a feature that is commonly found in functional programming languages. According to Scala documentation , pattern matching is “a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts.”

This is not to be confused with Regex, string matching, or pattern recognition. Pattern matching has nothing to do with string, but instead data structure. The first time I encountered pattern matching was around two years ago when I tried out Elixir . I was learning Elixir and trying to solve algorithms with it. I compared my solution to others and realized they used pattern matching, which made their code a lot more succinct and easier to read.

Because of that, pattern matching really made an impression on me. This is what pattern matching in Elixir looks like:

The example above looks very much like a multiple assignment in Ruby. However, it is more than that. It also checks whether or not the values match:

In the examples above, the number 42 on the left hand side isn’t a variable that is being assigned. It is a value to check that the same element in that particular index matches that of the right hand side.

In this example, instead of the values being assigned, MatchError is raised instead. This is because the number 88 does not match number 42.

It also works with maps (which is similar to hash in Ruby):

The example above checks that the value of the key name is Zote , and binds the value of the key title to the variable title.

This concept works very well when the data structure is complex. You can assign your variable and check for values or types all in one line.

Furthermore, It also allows a dynamically typed language like Elixir to have method overloading:

Depending on the key of the hash of the argument, different methods get executed.

Hopefully, that shows you how powerful pattern matching can be. There are many attempts to bring pattern matching into Ruby with gems such as noaidi , qo , and egison-ruby .

Ruby 2.7 also has its own implementation not too different from these gems, and this is how it’s being done currently.

Ruby Pattern Matching Syntax

Pattern matching in Ruby is done through a case statement. However, instead of using the usual when , the keyword in is used instead. It also supports the use of if or unless statements:

Case statement can accept a variable or an expression and this will be matched against patterns provided in the in clause. If or unless statements can also be provided after the pattern. The equality check here also uses === like the normal case statement. This means you can match subsets and instance of classes. Here is an example of how you use it:

Matching Arrays

In the example above, the variable translation gets matched against two patterns:

['th', orig_text, 'en', trans_text] and ['th', orig_text, 'ja', trans_text] . What it does is to check if the values in the pattern match the values in the translation variable in each of the indices. If the values do match, it assigns the values in the translation variable to the variables in the pattern in each of the indices.

Matching Hashes

In the example above, the translation variable is now a hash. It gets matched against another hash in the in clause. What happens is that the case statement checks if all the keys in the pattern matches the keys in the translation variable. It also checks that all the values for each key match. It then assigns the values to the variable in the hash.

Matching subsets

The quality check used in pattern matching follows the logic of === .

Multiple Patterns

  • | can be used to define multiple patterns for one block.

In the example above, the translation variable is match against both the {orig_lang: 'th', trans_lang: 'ja', orig_txt: orig_txt, trans_txt: trans_txt} hash and the ['th', orig_text, 'ja', trans_text] array.

This is useful when you have slightly different types of data structures that represent the same thing and you want both data structures to execute the same block of code.

Arrow Assignment

In this case, => can be used to assign matched value to a variable.

This is useful when you want to check values inside the data structure but also bind these values to a variable.

Pin Operator

Here, the pin operator prevents variables from getting reassigned.

In the example above, variable a in the pattern is matched against 1, 2, and then 2. It will be assigned to 1, then 2, then to 2. This isn’t an ideal situation if you want to check that all the values in the array are the same.

When the pin operator is used, it evaluates the variable instead of reassigning it. In the example above, [1,2,2] doesn’t match [a,^a,^a] because in the first index, a is assigned to 1. In the second and third, a is evaluated to be 1, but is matched against 2.

However [a,b,^b] matches [1,2,2] since a is assigned to 1 in the first index, b is assigned to 2 in the second index, then ^b, which is now 2, is matched against 2 in the third index so it passes.

Variables from outside the case statement can also be used as shown in the example above.

Underscore ( _ ) Operator

Underscore ( _ ) is used to ignore values. Let’s see it in a couple of examples:

In the two examples above, any value that matches against _ passes. In the second case statement, => operator captures the value that has been ignored as well.

Use Cases for Pattern Matching in Ruby

Imagine that you have the following JSON data:

In your Ruby project, you want to parse this data and display the name with the following conditions:

  • If the username exists, return the username.
  • If the nickname, first name, and last name exist, return the nickname, first name, and then the last name.
  • If the nickname doesn’t exist, but the first and last name do, return the first name and then the last name.
  • If none of the conditions apply, return “New User.”

This is how I would write this program in Ruby right now:

Now, let’s see what it looks like with pattern matching:

Syntax preference can be a little subjective, but I do prefer the pattern matching version. This is because pattern matching allows us to write out the hash we expect, instead of describing and checking the values of the hash. This makes it easier to visualize what data to expect:

Instead of:

Deconstruct and Deconstruct_keys

There are two new special methods being introduced in Ruby 2.7: deconstruct and deconstruct_keys . When an instance of a class is being matched against an array or hash, deconstruct or deconstruct_keys are called, respectively.

The results from these methods will be used to match against patterns. Here is an example:

The code defines a class called Coordinate . It has x and y as its attributes. It also has deconstruct and deconstruct_keys methods defined.

Here, an instance of Coordinate is being defined and pattern matched against an array. What happens here is that Coordinate#deconstruct is called and the result is used to match against the array [a,b] defined in the pattern.

In this example, the same instance of Coordinate is being pattern-matched against a hash. In this case, the Coordinate#deconstruct_keys result is used to match against the hash {x: x, y: y} defined in the pattern.

An Exciting Experimental Feature

Having first experienced pattern matching in Elixir, I had thought this feature might include method overloading and implemented with a syntax that only requires one line. However, Ruby isn’t a language that is built with pattern matching in mind, so this is understandable.

Using a case statement is probably a very lean way of implementing this and also does not affect existing code (apart from deconstruct and deconstruct_keys methods). The use of the case statement is actually similar to that of Scala’s implementation of pattern matching.

Personally, I think pattern matching is an exciting new feature for Ruby developers . It has the potential to make code a lot cleaner and make Ruby feel a bit more modern and exciting. I would love to see what people make of this and how this feature evolves in the future.

Understanding the basics

What is pattern matching in functional programming.

According to Scala documentation, pattern matching is “a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts.”

Why is pattern matching useful?

It has the potential to make code a lot cleaner and make Ruby feel a bit more modern and exciting.

How does pattern matching work?

Through switch case statement in Ruby 2.7, using the keyword “in” instead of the usual “when.”

What is meant by pattern matching?

  • PatternMatching

Noppakun Wongsrinoppakun

Bangkok, Thailand

Member since December 14, 2017

About the author

World-class articles, delivered weekly.

Subscription implies consent to our privacy policy

Toptal Developers

  • Algorithm Developers
  • Angular Developers
  • AWS Developers
  • Azure Developers
  • Big Data Architects
  • Blockchain Developers
  • Business Intelligence Developers
  • C Developers
  • Computer Vision Developers
  • Django Developers
  • Docker Developers
  • Elixir Developers
  • Go Engineers
  • GraphQL Developers
  • Jenkins Developers
  • Kotlin Developers
  • Kubernetes Experts
  • Machine Learning Engineers
  • Magento Developers
  • .NET Developers
  • R Developers
  • React Native Developers
  • Ruby on Rails Developers
  • Salesforce Developers
  • SQL Developers
  • Tableau Developers
  • Unreal Engine Developers
  • Xamarin Developers
  • View More Freelance Developers

Join the Toptal ® community.

  • Read from Text File
  • Write to File
  • Local Variable Declaration
  • If Statement
  • Case Statement
  • Do-While Loop
  • Exception Handling
  • Ternary Operator
  • Throw and Catch
  • Class Declaration & Structure
  • Class and Instance Variables
  • Constructor
  • Instantiation
  • Inheritance
  • Class Methods

Version: 2.2.0

Control flow, case statement in ruby.

Used to test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed. A break statement ends the switch case. The optional default case is for when the variable does not equal any of the cases.

As seen above, ranges can be used in a case statement.

Add to Slack

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.

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

  •   

Home Classes Methods

  • keywords.rb

BasicObject

  • #__ENCODING__

Class/Module Index

Public instance methods.

Designates, via code block, code to be executed unconditionally before sequential execution of the program begins. Sometimes used to simulate forward references to methods.

Designates, via code block, code to be executed just prior to program termination.

The current default encoding, as an Encoding instance.

Denotes the end of the regular source code section of a program file. Lines below __END__ will not be executed. Those lines will be available via the special filehandle DATA . The following code will print out two stanzas of personal information. Note that __END__ has to be flush left, and has to be the only thing on its line.

The name of the file currently being executed, including path relative to the directory where the application was started up (or the current directory, if it has been changed). The current file is, in some cases, different from the startup file for the running application, which is available in the global variable $0 .

The line number, in the current source file, of the current line.

Creates an alias or duplicate method name for a given method. The original method continues to be accessible via the alias, even if it is overriden. Takes two method-name arguments (which can be represented by strings or symbols but can also be the bare names themselves).

Boolean and operator. Differs from && in that and has lower precedence. In this example:

the subexpression puts "Hello" is executed first, and returns nil . The whole expression thus reduces to:

which reduces to nil . In this example, however:

the expression "Hello" && "Goodbye" is used as the argument to puts . This expression evaluates to “Goodbye”; therefore, the whole statement prints “Goodbye”.

Together with end , delimits what is commonly called a “begin” block (to distinguish it from the Proc type of code block). A “begin” block allows the use of while and until in modifier position with multi-line statements:

“Begin” blocks also serve to scope exception raising and rescue operations. See rescue for examples. A “begin” block can have an else clause, which serves no purpose (and generates a warning) unless there’s also a rescue clause, in which case the else clause is executed when no exception is raised.

Causes unconditional termination of a code block or while or until block, with control transfered to the line after the block. If given an argument, returns that argument as the value of the terminated block.

The case statement operator. Case statements consist of an optional condition, which is in the position of an argument to case , and zero or more when clauses. The first when clause to match the condition (or to evaluate to Boolean truth, if the condition is null) “wins”, and its code stanza is executed. The value of the case statement is the value of the successful when clause, or nil if there is no such clause.

A case statement can end with an else clause. Each when statement can have multiple candidate values, separated by commas.

Case equality (success by a when candidate) is determined by the case-equality or “threequal” operator, === . The above example is equivalent to:

=== is typically overriden by classes to reflect meaningful case-statement behavior; for example, /abc/ === "string" checks for a pattern match from the string.

Opens a class definition block. Takes either a constant name or an expression of the form << object . In the latter case, opens a definition block for the singleton class of object .

Classes may be opened more than once, and methods and constants added during those subsequent openings. class blocks have their own local scope; local variables in scope already are not visible inside the block, and variables created inside the block do not survive the block.

Inside a class block, self is set to the class object whose block it is. Thus it’s possible to write class methods (i.e., singleton methods on class objects) by referring to self :

Paired with a terminating end , constitutes a method definition. Starts a new local scope; local variables in existence when the def block is entered are not in scope in the block, and local variables created in the block do not survive beyond the block.

def can be used either with or without a specific object:

def method_name

def object.singleton_method_name

The parameter list comes after the method name, and can (and usually is) wrapped in parentheses.

defined? expression tests whether or not expression refers to anything recognizable (literal object, local variable that has been initialized, method name visible from the current scope, etc.). The return value is nil if the expression cannot be resolved. Otherwise, the return value provides information about the expression.

Note that the expression is not executed.

Assignment to a local variable will, however, have the usually result of initializing the variable to nil by virtue of the assignment expression itself:

In most cases, the argument to defined? will be a single identifier:

Paired with end , can delimit a code block:

In this context, do / end is equivalent to curly braces, except that curly braces have higher precedence. In this example:

the code block binds to map ; thus the output is:

In this version, however:

the code is interpreted as puts([1,2,3].map) do |x| x * 10 end . Since puts doesn’t take a block, the block is ignored and the statement prints the value of the blockless [1,2,3].map (which returns an Enumerator).

do can also (optionally) appear at the end of a for / in statement. (See for for an example.)

The else keyword denotes a final conditional branch. It appears in connection with if , unless , and case , and rescue . (In the case of rescue , the else branch is executed if no exception is raised.) The else clause is always the last branch in the entire statement, except in the case of rescue where it can be followed by an ensure clause.

Introduces a branch in a conditional ( if or unless ) statement. Such a statement can contain any number of elsif branches, including zero.

See if for examples.

Marks the end of a while , until , begin , if , def , class , or other keyword-based, block-based construct.

Marks the final, optional clause of a begin / end block, generally in cases where the block also contains a rescue clause. The code in the ensure clause is guaranteed to be executed, whether control flows to the rescue block or not.

If the statement 1/0 is changed to something harmless, like 1/1 , the rescue clause will not be executed but the ensure clause still will.

false denotes a special object, the sole instance of FalseClass . false and nil are the only objects that evaluate to Boolean falsehood in Ruby (informally, that cause an if condition to fail.)

A loop constructor, used with in :

for is generally considered less idiomatic than each ; indeed, for calls each , and is thus essentially a wrapper around it.

The do keyword may optionally appear at the end of the for expression:

Ruby’s basic conditional statement constructor. if evaluates its argument and branches on the result. Additional branches can be added to an if statement with else and elsif .

An if statement can have more than one elsif clause (or none), but can only have one else clause (or none). The else clause must come at the end of the entire statement.

if can also be used in modifier position:

then may optionally follow an if condition:

Opens a module definition block. Takes a constant (the name of the module) as its argument. The definition block starts a new local scope; existing variables are not visible inside the block, and local variables created in the block do not survive the end of the block.

Inside the module definition, self is set to the module object itself.

Bumps an iterator, or a while or until block,to the next iteration, unconditionally and without executing whatever may remain of the block.

next is typically used in cases like iterating through a list of files and taking action (or not) depending on the filename.

next can take a value, which will be the value returned for the current iteration of the block.

A special “non-object”. nil is, in fact, an object (the sole instance of NilClass ), but connotes absence and indeterminacy. nil and false are the only two objects in Ruby that have Boolean falsehood (informally, that cause an if condition to fail).

nil serves as the default value for uninitialized array elements and hash values (unless the default is overridden).

Boolean negation.

Similar in effect to the negating bang ( ! ), but has lower precedence:

(The unary ! also differs in that it can be overridden.)

Boolean or. Differs from || in that or has lower precedence. This code:

is interpreted as (puts "Hi") or "Bye" . Since puts "Hi" reduces to nil , the whole expression reduces to nil or "Bye" which evaluates to "Bye" . (The side-effect printing of “Hi” does take place.)

This code, however:

is interpreted as puts("Hi" || "Bye") , which reduces to puts "Hi" (since "Hi" || "Bye" evaluates to "Hi" ).

Causes unconditional re-execution of a code block, with the same parameter bindings as the current execution.

Designates an exception-handling clause. Can occur either inside a begin<code>/<code>end block, inside a method definition (which implies begin ), or in modifier position (at the end of a statement).

By default, rescue only intercepts StandardError and its descendants, but you can specify which exceptions you want handled, as arguments. (This technique does not work when rescue is in statement-modifier position.) Moreover, you can have more than one rescue clause, allowing for fine-grained handling of different exceptions.

In a method (note that raise with no argument, in a rescue clause, re-raises the exception that’s being handled):

In a begin / end block:

In statement-modifier position:

rescue (except in statement-modifier position) also takes a special argument in the following form:

which will assign the given local variable to the exception object, which can then be examined inside the rescue clause.

Inside a rescue clause, retry causes Ruby to return to the top of the enclosing code (the begin keyword, or top of method or block) and try executing the code again.

Inside a method definition, executes the ensure clause, if present, and then returns control to the context of the method call. Takes an optional argument (defaulting to nil), which serves as the return value of the method. Multiple values in argument position will be returned in an array.

Inside a code block, the behavior of return depends on whether or not the block constitutes the body of a regular Proc object or a lambda-style Proc object. In the case of a lambda, return causes execution of the block to terminate. In the case of a regular Proc, return attempts to return from the enclosing method. If there is no enclosing method, it’s an error.

self is the "current object" and the default receiver of messages (method calls) for which no explicit receiver is specified. Which object plays the role of self depends on the context.

In a method, the object on which the method was called is self

In a class or module definition (but outside of any method definition contained therein), self is the class or module object being defined.

In a code block associated with a call to class_eval (aka module_eval ), self is the class (or module) on which the method was called.

In a block associated with a call to instance_eval or instance_exec , self is the object on which the method was called.

self automatically receives message that don't have an explicit receiver:

In this method definition, the message upcase goes to self , which is whatever string calls the method.

Called from a method, searches along the method lookup path (the classes and modules available to the current object) for the next method of the same name as the one being executed. Such method, if present, may be defined in the superclass of the object’s class, but may also be defined in the superclass’s superclass or any class on the upward path, as well as any module mixed in to any of those classes.

Called with no arguments and no empty argument list, super calls the appropriate method with the same arguments, and the same code block, as those used to call the current method. Called with an argument list or arguments, it calls the appropriate methods with exactly the specified arguments (including none, in the case of an empty argument list indicated by empty parentheses).

Optional component of conditional statements ( if , unless , when ). Never mandatory, but allows for one-line conditionals without semi-colons. The following two statements are equivalent:

See if for more examples.

The sole instance of the special class TrueClass. true encapsulates Boolean truth; however, <emph>all</emph> objects in Ruby are true in the Boolean sense (informally, they cause an if test to succeed), with the exceptions of false and nil .

Because Ruby regards most objects (and therefore most expressions) as “true”, it is not always necessary to return true from a method to force a condition to succeed. However, it’s good practice to do so, as it makes the intention clear.

Undefines a given method, for the class or module in which it’s called. If the method is defined higher up in the lookup path (such as by a superclass), it can still be called by instances classes higher up.

Note that the argument to undef is a method name, not a symbol or string.

The negative equivalent of if .

The inverse of while : executes code until a given condition is true, i.e., while it is not true. The semantics are the same as those of while ; see while .

while takes a condition argument, and executes the code that follows (up to a matching end delimiter) while the condition is true.

The value of the whole while statement is the value of the last expression evaluated the last time through the code. If the code is not executed (because the condition is false at the beginning of the operation), the while statement evaluates to nil .

while can also appear in modifier position, either in a single-line statement or in a multi-line statement using a begin / end block. In the one-line case:

i = 0 i += 1 while i < 10

the leading code is not executed at all if the condition is false at the start. However, in the “begin”-block case:

the block will be executed at least once, before the condition is tested the first time.

Called from inside a method body, yields control to the code block (if any) supplied as part of the method call. If no code block has been supplied, calling yield raises an exception.

yield can take an argument; any values thus yielded are bound to the block's parameters. The value of a call to yield is the value of the executed code block.

Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.

If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists . You will get better, faster, help that way.

If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.

If you want to help improve the Ruby documentation, please see Improve the docs , or visit Documenting-ruby.org .

Generated with the Ruby-doc Rdoc Generator 0.23.5 .

IMAGES

  1. Ruby Case Statement

    ruby case statement assignment

  2. Ruby

    ruby case statement assignment

  3. Ruby Case Statements (Full Tutorial With Examples)

    ruby case statement assignment

  4. Using Case Statements in Ruby. As a true beginner, every line of code

    ruby case statement assignment

  5. Case statement in Ruby

    ruby case statement assignment

  6. Decision Making in Ruby (if else)

    ruby case statement assignment

VIDEO

  1. Explain the [Next statement] in RUBy || copycat

  2. Ruby Programming Control Statement

  3. If Statement Assignment

  4. Ruby Franke Wants Forgiveness? Therapist Reacts!

  5. Hunter assignment Ruby game

  6. Switch Statement Assignment

COMMENTS

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

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

  3. Ruby

    Ruby | Case Statement. The case statement is a multiway branch statement just like a switch statement in other languages. It provides an easy way to forward execution to different parts of code based on the value of the expression. There are 3 important keywords which are used in the case statement: case: It is similar to the switch keyword in ...

  4. Ruby Case Statement: Detailed Guide

    Structure of a Ruby Case Statement. A Ruby case statement is structured around several key components: case: Initiates the case statement, evaluating the variable in question; when: Represents individual conditions to be matched; else: Executes an alternative action if no conditions match, though this is optional. Utilizing Case Statements with ...

  5. Ruby's case statement

    Actually, case statements in Ruby are a lot richer and more complex than you might imagine. Let's take a look at just one example: case "Hi there" when String puts "case statements match class" end # outputs: "case statements match class". This example shows that case statements not only match an item's value but also its class.

  6. control_expressions

    a = 2 case when a == 1, a == 2 puts "a is one or two" when a == 3 puts "a is three" else puts "I don't know what a is" end. Again, the then and else are optional. The result value of a case expression is the last value executed in the expression. Since Ruby 2.7, case expressions also provide a more powerful experimental pattern matching feature ...

  7. How A Ruby Case Statement Works And What You Can Do With It

    So, you can safely wrap a case statement in a method call and Ruby will have no problems with it. For example, the above version of the case statement ca be re-written like this: ruby. print "Enter a string: ". some_string = gets.chomp. puts case. when some_string.match(/\d/) 'String has numbers'.

  8. How do I use 'case' statements in Ruby?

    fruit = 'apple'. case fruit. when 'apple' then puts "It's an apple." when 'banana' then puts "It's a banana." else puts "It's something else." end. ```. The `case` statement in Ruby provides a clean and organized way to handle multiple conditions, making your code more readable and maintainable.

  9. How to Use the Case/Switch Statement in Ruby

    The case statement in Ruby, on the other hand, can be seen as a shorthand for a series of if statements. There is no fallthrough, only the first matching case will be executed. ... Case Assignment . Like if statements, case statements evaluate to the last statement in the when clause. In other words, they can be used in assignments to provide a ...

  10. How to perform conditional logic effectively with Ruby

    Similar in many ways to Java's switch statement, Ruby's case, when and else block statements are analogous to Java's switch, case and default semantics. Here's how we would implement the conditional logic of the roshambo application using Ruby's case statement: case. when client_gesture == "rock". outcome = "tie".

  11. Ruby Language Tutorial => Case statement

    As per the Ruby Docs: Case statements consist of an optional condition, which is in the position of an argument to case, and zero or more when clauses. The first when clause to match the condition (or to evaluate to Boolean truth, if the condition is null) "wins", and its code stanza is executed. The value of the case statement is the value ...

  12. Introduction to Pattern Matching in Ruby

    The example above looks very much like a multiple assignment in Ruby. However, it is more than that. It also checks whether or not the values match: [a, b, 42] = [:hello, "world", 42] a #=> :hello b #=> "world" ... Pattern matching in Ruby is done through a case statement. However, instead of using the usual when, ...

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

  14. Learn Ruby: Refactoring Cheatsheet

    Ruby Case Statement. In Ruby, a case statement is a more concise alternative to an if/else statement that contains many conditions. tv_show = "Bob's Burgers" ... In Ruby, a conditional assignment operator (||=) assigns a real value to a variable only when its current value is false or nil. Otherwise, Ruby keeps its original value.

  15. Case Statement in Ruby

    Case Statement in Ruby. Used to test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed. A break statement ends the switch case. The optional default case is for when the variable does not equal any of the cases. Syntax

  16. Programming Ruby: The Pragmatic Programmer's Guide

    For example, the if and case statements both return the value of the last expression executed. songType = if song.mp3Type == MP3::Jazz if song.written < Date.new(1935, 1, 1) Song::TradJazz else Song::Jazz end else Song::Other end ... As of Ruby 1.6.2, if an assignment has one lvalue and multiple rvalues, the rvalues are converted to an array ...

  17. Conditional Statements in Ruby

    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: day = "Monday" case day when "Monday" puts "It's the beginning of the week." when "Friday" puts "It's the end of the week!"

  18. ruby

    You're using the first form when you think you're using the second form so you end up doing strange (but syntactically valid) things like: (guess > @answer) === guess. (guess < @answer) === guess. In either case, case is an expression and returns whatever the matched branch returns. edited Jan 4, 2019 at 19:39.

  19. Class: Object

    The case statement operator. Case statements consist of an optional condition, which is in the position of an argument to case, and zero or more when clauses. The first when clause to match the condition (or to evaluate to Boolean truth, if the condition is null) "wins", and its code stanza is executed. The value of the case statement is the value of the successful when clause, or nil if ...