Rubyケース・ステートメントの手引き

Rubyケース文入門ガイド

The case statement in Ruby is a versatile and powerful tool for handling multiple conditions in a clean, readable format. Whether you’re a beginner or just need a refresher, this guide will take you through the basics of case statements, with practical examples to solidify your understanding.

What is a Ruby Case Statement?

case statement is an alternative to the if-elsif-else structure, designed to make code more concise and easier to read. It evaluates an expression and executes code based on matching conditions.

Basic Syntax

case expression
when condition1
  # Code to execute if condition1 is true
when condition2
  # Code to execute if condition2 is true
それ以外
  # Code to execute if no conditions match
終わり

Example 1: Simple Case Statement

ruby

Copy code
day = "Monday"
case day
when "Monday" puts "Start of the workweek!" when "Friday" puts "Almost weekend!" else puts "Just another day." end

出力:
Start of the workweek!

Example 2: Using Ranges

You can match ranges of values within a case statement.

grade = 85

case grade

when 90..100

  puts "Excellent"

when 80..89

  puts "Good"

when 70..79

  puts "Average"

else

  puts "Needs Improvement"

end

出力:
Good

Example 3: Multiple Conditions in a Single Line

Combine conditions with commas for simplicity.

weather = "rainy"

case weather

when "sunny", "partly cloudy"

  puts "Go for a walk!"

when "rainy", "stormy"

  puts "Stay indoors."

else

  puts "Check the forecast."

end

出力:
Stay indoors.

Example 4: Using case with then

For shorter statements, use then for inline execution.

number = 5
case number
when 1 then puts "One"
when 5 then puts "Five"
else puts "Other number"
終わり

出力:
Five

Example 5: Pattern Matching with case

Introduced in Ruby 2.7, pattern matching adds more power to case.

value = [1, 2, 3]

case value

in [1, _, _]

  puts "Starts with 1"

in [_, _, 3]

  puts "Ends with 3"

else

  puts "Different pattern"

end

出力:
Starts with 1

When to Use a Ruby Case Statement?

  • When you have multiple conditions to evaluate.
  • To improve readability compared to if-elsif-else.
  • When matching ranges, arrays, or specific patterns.

Tips for Mastering Case Statements

  1. Keep it Simple: Avoid overly complex conditions.
  2. Use Default (それ以外): Always provide a fallback condition.
  3. Leverage Ranges and Patterns: Simplify logic with Ruby’s range and pattern matching features.

結論

Ruby’s case statement is a powerful feature that simplifies condition handling. Whether you’re evaluating simple expressions, ranges, or patterns, mastering the case statement will enhance your Ruby programming skills. レールカーマ provides expert Ruby on Rails developers to deliver scalable, high-quality solutions tailored to your project’s unique needs.

関連記事

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

jaJapanese