5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby で (a ==1 && a== 2 && a==3) の結果を真にする

5
Posted at

ブログ記事からの転載です。

と、いうのが JavaScript 界隈で流行っているので Ruby でもやってみた

== メソッドを定義する

多分一番簡単なやり方。
比較演算子そのものの結果を変えます。

a = Object.new
def a.== other
	true
end

p a == 1 && a == 2 && a == 3
# => true

a メソッドを定義する

Ruby ではメソッド呼び出しの際に () を省略する事が出来るので a() というメソッド呼び出しを a とだけで呼び出すことが出来ます。

def a
	@a = (@a || 0) + 1
end

p a == 1 && a == 2 && a == 3
# => true

こっちは Ruby らしいですね。

おまけ:== ではなくて === を使う

主題からは外れますが Ruby では === 演算子は特別な呼び出しなので == の変わりに === を使うといろいろな手段が使えます。

Proc#=== を使う

Proc#===Proc#call と同じなのでブロックの中身をそのまま返します。

a = proc { true }

# a.call 1 と同じ
p a === 1 && a === 2 && a === 3
# => true

Method#=== を使う

Method#===Proc#=== と同様に #call を呼び出します。

a = [1, 2, 3].method(:include?)

# [1, 2, 3].include? 1 を呼び出しているのと同じ
p a === 1 && a === 2 && a === 3
# => true

Range#=== を使う

Range#===Range#include? を呼び出します。

a = (1..3)

# (1..3).include? 1 を呼び出しているのと同じ
p a === 1 && a === 2 && a === 3
# => true

Set#=== を使う

Range と同様に Set#===Set#include? を呼び出します。

require "set"

a = Set[1, 2, 3]

# Set[1, 2, 3].include? 1 を呼び出しているのと同じ
p a === 1 && a === 2 && a === 3
# => true

Ruby たのしい

5
0
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
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?