Ruby 4-1-1

こんにちは!

大阪ダービーはあれでしたが、シーズンはまだ残っています。

条件分岐

if文などの説明を行っていきます。

if_basic.rb
Image from Gyazo

Image from Gyazo

一番基本的な形です。

if_nolese.rb
Image from Gyazo

Image from Gyazo

一つの条件だけを処理する場合はelse以降の省略が可能です。

if_then.rb
Image from Gyazo

Image from Gyazo

thenを記述できますが、一般的には省略されます。

if_then2.rb
Image from Gyazo

Image from Gyazo

ifを1行で表す場合、thenの省略はできません。
ただし、そもそも複数の文を1行でまとめることは良い習慣ではありません。

if_after.rb
Image from Gyazo

Image from Gyazo

後置if構文です。

if_exp.rb
Image from Gyazo

Image from Gyazo

ifは式として利用することができます。

if_else.rb
Image from Gyazo

Image from Gyazo

elsifを用いることで多岐分岐も表現できます。

if_else2.rb
Image from Gyazo

Image from Gyazo

最初の条件式から評価されるため、正しい順序での記述に気を付けましょう。

if_nest.rb
Image from Gyazo

Image from Gyazo

if文は入れ子に記述することができます。
このような記述をネストするといいます。

unless_basic.rb
Image from Gyazo

Image from Gyazo

unless文は条件式が偽の場合に実行されます。

unless_exp.rb
Image from Gyazo

Image from Gyazo

unlessも式として利用できます。

unless_after.rb
Image from Gyazo

Image from Gyazo

unlessも後置構文で表現できます。

case_pre.rb
Image from Gyazo

Image from Gyazo

「変数 == 値」の条件式が並んでいるため、見た目に冗長に感じます。

case_basic.rb
Image from Gyazo

Image from Gyazo

case...when命令を用いてすっきりと表現できます。

case_then.rb
Image from Gyazo

Image from Gyazo

thenを用いることで、1行にまとめることが可能です。

ちなみに、whenの値が特定の型を取る場合、判定ルールが変化します。

case_range.rb
Image from Gyazo

Image from Gyazo

Range型、範囲内に収まっているかを判定します。

case_class.rb
Image from Gyazo

Image from Gyazo

Module/Class型、値がその型か、派生型かを判定します。

case_regexp.rb
Image from Gyazo

Image from Gyazo

Regexp型、正規表現パターンにマッチするかを判定します。

case_set.rb
Image from Gyazo

Image from Gyazo

Set型、式の値がSetの集合に含まれているかを判定します。

case_method.rb
Image from Gyazo

Image from Gyazo

Method型、メソッドを実行した戻り値が真かを判定します。
def命令に関しては、8章で詳しく取り扱うとのことです。

case_cond.rb
Image from Gyazo

Image from Gyazo

when節に条件式を指定することも可能ですが、これであればifのほうが素直です。

case_exp.rb
Image from Gyazo

Image from Gyazo

caseも式として表すことが可能です。

内容はもう少しありますが、長くなってきましたのでここで一度切ります。

ではでは。