The Wayback Machine - https://web.archive.org/web/20240926141006/https://www.geeksforgeeks.org/ruby-case-statement/
Open In App

Ruby | Case Statement

Last Updated : 26 Oct, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Syntax:

case expression

when expression 1
  # your code

when expression 2
  # your code
.
.

else
  # your code
end

Flow Chart:

Example 1:




# Ruby program to illustrate the 
# concept of case statement
  
#!/usr/bin/ruby   
  
print "Input from one, two, three, four: "  
  
# taking input from user
# str = gets.chomp
  
# hardcoded input
str = "two"
  
# using case statement
case str 
  
# using when
when "one"  
  puts 'Input is 1'
  
when "two"  
  puts 'Input is 2'
  
when "three"  
  puts 'Input is 3'
  
 when "four"  
  puts 'Input is 4'
  
else  
  puts "Default!"
  
end  


Output:

Input from one, two, three, four: Input is 2

Example 2:




# Ruby program to illustrate
# case statement
  
#!/usr/bin/ruby
  
marks = 70
  
# marks is the input
# for case statement
case marks
  
# using range operators ..
when 0..32
  puts "You fail!"
  
when 33..40
  puts "You got C grade!"
  
when 41..60
  puts "You got B grade!"
  
else
 puts  "You got A grade!"
   
end


Output:

You got A grade!

Important Points:

  • In case statement the when statement can contain multiple values and range(see above example).

    Example:




    # Ruby program to illustrate 
    # how to use multiple values 
    # in when statement
      
    choice = "5"
      
    # using 'case' statement
    case choice
          
        # here 'when' statement contains
        # the two values
        when "1","2"
            puts "You order Espresso!"
          
        when "3","4"
            puts "You order Short Macchiato!"
          
        when "5","6"
            puts "You order Ristretto!"
          
        when "7","8"
            puts "You order Cappuccino!"
          
    else
        "No Order!"
    end

    
    

    Output:

    You order Ristretto!
    
  • You can also use case statement without any value.

    Example:




    # Ruby program to illustrate no 
    # value in case statement
      
    str = "GeeksforGeeks"
      
    # here case statement 
    # has no value
    case
          
        # using match keyword to check
        when str.match(/\d/)
              puts 'String contains numbers'
          
        when str.match(/[a-zA-Z]/)
              puts 'String contains letters'
    else
        puts 'String does not contain numbers & letters'
    end

    
    

    Output:

    String contains letters
  • You can use case statement in method call. Like method call, a case statement will always return a single object.

    Example:




    # Ruby program to illustrate case 
    # statement in a method call
      
    str = "1234"
      
    # here case statement 
    # has no value & used as 
    # in puts method call
    puts case
          
        # using match keyword to check
        when str.match(/\d/)
                
            'String contains numbers'
          
        when str.match(/[a-zA-Z]/)
                
            'String contains letters'
    else
          
        'String does not contain numbers & letters'
    end

    
    

    Output:

    String contains numbers
    

    Explanation: Here we are using the case statement in a puts method call. The benefit of doing this that we can omit the puts from the when statement.



Previous Article
Next Article

Similar Reads

How to Convert a String to Lower or Upper Case in Ruby?
In this article, we will discuss how to convert a string to lower or upper case in Ruby. We can convert a string to lower or upper case using built-in methods provided in the Ruby language. Table of Content Using DowncaseUsing UpcaseUsing CapitalizeUsing DowncaseThe downcase method is used to convert the string to lowercase. Syntax: string.downcase
2 min read
Ruby | unless Statement and unless Modifier
Ruby provides a special statement which is referred as unless statement. This statement is executed when the given condition is false. It is opposite of if statement. In if statement, the block executes once the given condition is true, however in unless statement, the block of code executes once the given condition is false. Unless statement is us
2 min read
Ruby redo and retry Statement
In Ruby, Redo statement is used to repeat the current iteration of the loop. redo always used inside the loop. The redo statement restarts the loop without evaluating the condition again. # Ruby program of using redo statement #!/usr/bin/ruby restart = false # Using for loop for x in 2..20 if x == 15 if restart == false # Printing values puts
2 min read
Difference between Ruby and Ruby on Rails
Ruby is an object-oriented scripting language known for its simplicity and security, commonly used in developing desktop applications. Ruby on Rails is a web application framework built on Ruby, designed for creating database-driven web apps using the MVC architecture. It emphasizes principles like "Don’t Repeat Yourself" (DRY) and is known for its
4 min read
Private Classes in Ruby
The concept of private, protected and public methods in Ruby is a bit different than it other languages like Java. In Ruby, it is all about which class the person is calling, as classes are objects in ruby. Private Class When a constant is declared private in Ruby, it means this constant can never be called with an explicit receiver, a private cons
3 min read
Ruby | Matrix cofactor() function
The cofactor() is an inbuilt method in Ruby returns the cofactor of the given index. Syntax: mat1.cofactor(i, j) Parameters: The function needs two index i and j, whose cofactor is to be returned. Return Value: It returns the cofactor of the given index. Example 1: # Ruby program for cofactor() method in Matrix # Include matrix require "matrix
1 min read
Ruby Integer odd? function with example
The odd? function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false. Syntax: number.odd? Parameter: The function takes the integer which is to be checked for odd or not. Return Value: The function returns a boolean value which determines if the value is odd or not. Example #1: # Ruby program of integer odd
1 min read
Ruby Integer div() function with example
The div() function in Ruby returns the integer division of two numbers. Syntax: (number1).div(number2) Parameter: The function needs two numbers number1 and number2, where number1 is the dividend and number2 is the divisor. Return Value: The function returns the integer division of two numbers. Example #1: # Ruby program of Integer div() function #
1 min read
Ruby | Symbol to_s function
Symbol#to_s() : to_s() is a Symbol class method which returns string representation of the symbol object. Syntax: Symbol.to_s() Parameter: Symbol values Return: string representation of the symbol object. Example #1 : # Ruby code for Symbol.to_s() method # declaring Symbol a = :aBcDeF # declaring Symbol b = :"\u{e4 f6 fc}" # declaring Sym
1 min read
Ruby | Set replace() function
The replace() is an inbuilt method in Ruby which replaces the contents of the set with the contents of the given enumerable object and returns self. Syntax: s1.replace(enum) Parameters: The function accepts an enumerable object which to be replaced in the set. Return Value: It returns the self object which contains the contents of the set after rep
1 min read
Ruby | Set reset() function
The reset() is an inbuilt method in Ruby resets the internal state after modification to existing elements and returns self. The elements will be reindexed and deduplicated. Syntax: s1.reset() Parameters: The function does not accepts any parameter. Return Value: It returns self . Example 1: # Ruby program to illustrate # the reset() method # requi
1 min read
Ruby | Array Concatenation using (+) function
Array#+() is a Array class method which performs set concatenate operation arrays by combining two arrays to a third array. Syntax: Array.+() Parameter: Arrays for performing the concatenation operation. Return: New arrays by combining two arrays. Example #1 : # Ruby code for +() method # showing concatenate operation # declaring array a = [18, 22,
2 min read
Ruby | at() function
The at() function in Ruby is used to return the element of the specified index. Index 0 is for the first element of the array, 1 for the second element of the array and so on. The negative index counts from the end of the input array. Syntax: Array.at(Index) Here Array is the input array of elements at which at() function is called. Parameters: Ind
2 min read
Ruby Float to_r() method with example
Float to_r() is a float class method which return a rational form of the float value. Syntax: float.to_r() Parameter: float value as argument Return: Rational form representation of the float value. Example #1 : # Ruby code for to_r() method # Initializing values a = 2.0 b = 9.99991 # Printing result puts "Rational form of a : #{a.to_r}\n\n
1 min read
Ruby | Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects or as constants. Doing this may result in compile-time error. Example: # Ruby program to illustrate Keywords #!/usr/bin/ruby # here 'if' is a k
4 min read
Ruby | Exception Class and its Methods
An exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at runtime, that disrupts the normal flow of the program’s instructions. In Ruby, descendants of an Exception class are used to interface between raise methods and rescue statements in the begin or end blocks. Exception objects carry information ab
3 min read
Ruby | String inspect Method
inspect is a String class method in Ruby which is used to return a printable version of the given string, surrounded by quote marks, with special characters escaped. Syntax: str.inspect Parameters: Returns: Here, str is the given string. Example 1: # Ruby program to demonstrate # the inspect method # Taking a string and # using the method puts
1 min read
Ruby | String hex Method
hex is a String class method in Ruby which is used to treats the leading characters from the given string as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error. Syntax: str.hex Parameters: Here, str is the given string. Returns: A corresponding number. Example 1:
1 min read
Ruby | String include? Method
include? is a String class method in Ruby which is used to return true if the given string contains the given string or character. Syntax: str.include? Parameters: Here, str is the given string. Returns: true if the given string contains the given string or character otherwise false. Example 1: # Ruby program to demonstrate # the include? method #
1 min read
Ruby | Hash each_pair() function
Hash#each_pair() is a Hash class method which finds the nested value which calls block once for each pair in hash by passing the key_value pair as parameters. Syntax: Hash.each_pair() Parameter: Hash values Return: calls block once for key_value pair in hash with key_value pair as parameter otherwise Enumerator if no argument is passed. Example #1
2 min read
The yield Keyword in Ruby
We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with
2 min read
Ruby | Struct to_s() function
The to_s() is an inbuilt method in Ruby that returns a string with the value of the particular struct. Syntax: struct_name.to_s() Parameters: The function does not accepts any parameter. Return Value: It returns the value of struct. Example 1: # Ruby program for to_s method in struct # Include struct animals = Struct.new(:name, :speciality , :found
1 min read
Ruby | Date === function
Date#===() is a Date class method which checks whether the two Date objects are equal. Syntax: Date.===() Parameter: Date values Return: true if two date objects are equal otherwise return false Example #1 : # Ruby code for Date.===() method # loading date require 'date' # declaring Date a = Date.new(2019, 1, 1) # declaring Date b = Date.jd(2452004
2 min read
Ruby | Date <=>() method
Date#<=> is a Date class method which compares two date objects. Syntax: Date<=>b Parameter: Date values Return: 1 if a is greater than b -1 if a is less than b 0 if a equals b Example #1 : # Ruby code for Date.<=>() method # loading date require 'date' # declaring Date a = Date.new(2019, 1, 1) # declaring Date b = Date.jd(2452004
2 min read
Ruby | Date - function
Date#-() is a Date class method which returns the difference between two dates if the object is date type object. Syntax: Date.-() Parameter: Date values Return: difference between two dates Example #1 : # Ruby code for Date.-() method # loading date require 'date' # declaring Date a = Date.new(2019, 1, 1) # declaring Date b = Date.jd(2452004) # de
2 min read
Ruby | Date + method
Date#+() is a Date class method which adds a numeric value to the date and returns a date object pointing other days after self. Syntax: Date.+() Parameter: Date values Return: date object pointing other days after self after adding a numeric value to the date. Example #1 : # Ruby code for Date.+() method # loading date require 'date' # declaring D
2 min read
Ruby | Complex + method
Complex#+() : +() is a Complex class method which performs the addition operation. Syntax: Complex.+()Parameter: Complex valuesReturn: Addition Operation on complex values. Example #1 : C/C++ Code # Ruby code for Complex.+() method # declaring Complex value a = Complex(200) # declaring Complex value b = Complex(-1, 4) # declaring Complex value c =
1 min read
Ruby | Array cycle() operation
Array#cycle() : cycle() is a Array class method which returns the array by calling the given block each time for every element in the array 'n' no. of times and if 'nil' is given, then it will call it for forever. Syntax: Array.cycle() Parameter: block - condition n - number of times to call the block Return: array by calling the given block each t
2 min read
Ruby | Array delete() operation
Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array.delete() Parameter: obj - specific element to delete Return: last deleted values from the array. Code #1 : Example for delete() method C/C++ Code # Ruby code for delete(
2 min read
Ruby | Array delete_at() operation
Array#delete_at() : delete_at() is a Array class method which deletes the arrays elements at the mentioned index. Syntax: Array.delete_at() Parameter: index - value at specific index value to delete Return: deleted element, nil - if the index value is out of range Code #1 : Example for delete_at() method C/C++ Code # Ruby code for delete_at() metho
2 min read
Article Tags :