Ruby Class Case

The case statement in Ruby is used for more complex conditional flows where you might be used to using if...elsif...else. It's a way to replace multiple if statements and make your code more readable.

Here's a simple example of a case statement:

value = 2

case value
when 1
  puts "One"
when 2
  puts "Two"
when 3
  puts "Three"
else
  puts "Something else"
end

In this example, the case statement checks the value of value. Depending on the value, it executes a different when clause. If none of the when clauses match, it executes the else clause.

You can use the case statement with any kind of object, not just numbers. For example:

class Car
  attr_accessor :brand

  def initialize(brand)
    @brand = brand
  end

  def brand_type
    case @brand
    when "Toyota"
      "Japanese Car"
    when "Ford"
      "American Car"
    when "Ferrari"
      "Italian Car"
    else
      "Unknown Car"
    end
  end
end

car = Car.new("Ferrari")
puts car.brand_type  # outputs "Italian Car"

car.brand = "Ford"
puts car.brand_type  # outputs "American Car"

In this example, the case statement is used to determine the type of car based on the brand.

The case statement is a powerful tool in Ruby, and it can make your code more readable when you're dealing with complex conditional logic. It can be used in any context, not just within classes, and with any type of object, not just strings or numbers.

  1. Ruby class definition:

    • Description: In Ruby, a class is defined using the class keyword. It encapsulates data and behavior into a single unit.
    • Code example:
      class Person
        def initialize(name, age)
          @name = name
          @age = age
        end
      
        def display_info
          puts "Name: #{@name}, Age: #{@age}"
        end
      end
      
      # Object instantiation
      person = Person.new("John", 25)
      person.display_info
      
  2. Ruby class inheritance:

    • Description: Inheritance allows a class to inherit attributes and methods from another class.
    • Code example:
      class Animal
        def speak
          puts "Animal speaks"
        end
      end
      
      class Dog < Animal
        def bark
          puts "Dog barks"
        end
      end
      
      # Object instantiation
      dog = Dog.new
      dog.speak # Inherited method
      dog.bark  # Class-specific method
      
  3. Ruby class methods:

    • Description: Class methods are defined using the self keyword and can be called on the class itself.
    • Code example:
      class MathOperations
        def self.square(number)
          number * number
        end
      end
      
      # Using the class method
      result = MathOperations.square(5)
      
  4. Ruby case statement in class:

    • Description: A case statement in a class allows for multiple conditional branches based on the value of an expression.
    • Code example:
      class GradeClassifier
        def classify(grade)
          case grade
          when 'A'
            puts "Excellent"
          when 'B', 'C'
            puts "Good"
          else
            puts "Needs improvement"
          end
        end
      end
      
      # Using the class method
      classifier = GradeClassifier.new
      classifier.classify('B')
      
  5. Ruby switch case in class:

    • Description: The case statement is similar to a switch statement in other languages.
    • Code example:
      class TrafficLight
        def signal(color)
          case color
          when 'red'
            puts "Stop"
          when 'green'
            puts "Go"
          when 'yellow'
            puts "Proceed with caution"
          else
            puts "Invalid color"
          end
        end
      end
      
      # Using the class method
      traffic_light = TrafficLight.new
      traffic_light.signal('green')
      
  6. Ruby class example:

    • Description: An example of a simple Ruby class with methods and attributes.
    • Code example:
      class Car
        attr_accessor :make, :model
      
        def initialize(make, model)
          @make = make
          @model = model
        end
      
        def display_info
          puts "Make: #{@make}, Model: #{@model}"
        end
      end
      
      # Object instantiation
      car = Car.new("Toyota", "Camry")
      car.display_info
      
  7. Ruby class variables:

    • Description: Class variables are shared among all instances of a class and are prefixed with @@.
    • Code example:
      class Counter
        @@count = 0
      
        def increment
          @@count += 1
        end
      
        def display_count
          puts "Count: #{@@count}"
        end
      end
      
      # Object instantiation
      counter1 = Counter.new
      counter2 = Counter.new
      
      counter1.increment
      counter2.increment
      
      counter1.display_count # Outputs "Count: 2"
      
  8. Ruby class instance variables:

    • Description: Instance variables are specific to an instance of a class and are prefixed with @.
    • Code example:
      class Person
        def initialize(name)
          @name = name
        end
      
        def display_name
          puts "Name: #{@name}"
        end
      end
      
      # Object instantiation
      person = Person.new("Alice")
      person.display_name
      
  9. Ruby class access modifiers:

    • Description: Access modifiers (public, private, protected) control the visibility of methods in a class.
    • Code example:
      class BankAccount
        def deposit(amount)
          # Public method
        end
      
        private
      
        def withdraw(amount)
          # Private method
        end
      end
      
  10. Ruby class constructor:

    • Description: The constructor, often named initialize, is called when a new instance of a class is created.
    • Code example:
      class Book
        def initialize(title, author)
          @title = title
          @author = author
        end
      end
      
      # Object instantiation with constructor parameters
      book = Book.new("Ruby Programming", "John Doe")
      
  11. Ruby class initialization:

    • Description: Initialization is the process of setting up an object's initial state, often done in the constructor (initialize method).
    • Code example:
      class Circle
        def initialize(radius)
          @radius = radius
        end
      end
      
      # Object instantiation with initialization
      circle = Circle.new(5)
      
  12. Ruby class constants:

    • Description: Class constants are defined using uppercase letters and are accessible throughout the class.
    • Code example:
      class Constants
        PI = 3.14159
      
        def circle_area(radius)
          PI * radius**2
        end
      end
      
      # Using the class constant
      area = Constants.new.circle_area(3)
      
  13. Ruby class attributes:

    • Description: Attributes are often represented by instance variables and can be accessed using getter and setter methods or attr_accessor.
    • Code example:
      class Product
        attr_accessor :name, :price
      
        def initialize(name, price)
          @name = name
          @price = price
        end
      end
      
      # Object instantiation with attribute assignment
      product = Product.new("Laptop", 999)
      puts "Product: #{product.name}, Price: $#{product.price}"
      
  14. Ruby case-insensitive class comparison:

    • Description: When comparing strings in a case-insensitive manner, use methods like casecmp.
    • Code example:
      class StringComparison
        def compare_strings(str1, str2)
          result = str1.casecmp(str2)
          if result.zero?
            puts "Strings are equal"
          else
            puts "Strings are not equal"
          end
        end
      end
      
      # Using the class method
      comparer = StringComparison.new
      comparer.compare_strings("Ruby", "ruby") # Outputs "Strings are equal"