2
1

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.

配列要素の同値性を比較する

Posted at

配列の全要素が同じかどうかを比較するにはArray#uniqが使えます。

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1].uniq.size==1 # => true
[1, 1, 1, 1, 1, 1, 1, 2, 1, 1].uniq.size==1 # => false
%w(street retest setter tester).uniq { |w| w.chars.sort }.size==1 # => true

これをメソッドにしたArray#same?を考えました。

class Array
  def same?(&blk)
    self.uniq(&blk).size==1
  end
end

uniq同様、ブロックで同値性の条件を定義できます。

same?を使うと先の例は次のように簡潔に書けます。

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1].same? # => true
[1, 1, 1, 1, 1, 1, 1, 2, 1, 1].same? # => false
%w(street retest setter tester).same? { |w| w.chars.sort } # => true

RubyのメソッドArray#same?は要りませんか?

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?