🖥

Ruby | CASE文の中ではトリプルイコール ( === ) での比較がおこなわれる

に公開

コード

case 1
  when Numeric then puts 'It is numeric!'
  when String then puts 'It is string!'
end

# => It is numeric!
case 'abc'
  when Numeric then puts 'It is numeric!'
  when String then puts 'It is string!'
end

# => It is string!

解説

それぞれ

Numeric === 1 # => true
String === 'abc' # => true

とかいう比較がおこなわれているっぽい。

ちなみにクラス名との比較は、左右を逆にすると false が返る。

1 === Numeric # => false
'abc' === String # => false

結論

case 文は与える値 ( case *** ) ではなく、判定条件 ( when *** ) の方を左辺に持ってくるようだ。意外だった。

環境

  • ruby 2.3.1

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2016-12-05

Discussion