LoginSignup
2
1

More than 1 year has passed since last update.

Rubyでは最後に評価された値が戻り値になる

Last updated at Posted at 2023-04-20

Rubyでは最後に評価された値が戻り値となる。

メソッド

メソッドの最後に評価された値が戻り値になるため return は不要。

def hoge(n)
  'hoge'
  n
end

hoge(2) #=> 2

&& や ||

以下もtrueかfalseを返すと思いきや、最後に評価された値が返却される。

1 && 2 && 3 #=> 3
1 && nil && 3 #=> nil
nil || 5 #=> 5

xがnilなら初期値を渡す以下のようなテクニックをよく見るが、これも最終評価された値が戻り値になり、yに代入される。

y = x || 10

if

Rubyでは nilfalse のみ偽、それ以外は真と扱う。
以下だとifでの分岐判定処理の結果が3になり、真と判断される。

if 1 && 2 && 3
    # hoge
end
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1