0
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 3 years have passed since last update.

ruby Hash#==の挙動について

Posted at

ふとrubyにてHash同士の比較についてどこまで比較してるのか?と気になったので検証してみた。

結果としては公式のドキュメントに記載があるが
自身と other が同じ数のキーを保持し、キーが eql? メソッドで比較して全て等しく、値が == メソッドで比較して全て等しい場合に真を返します。

参考:instance method Hash#==

という動作をするようだ、検証してみる。

require 'securerandom'

keys   = Array.new
values = Array.new

# 1000個のテストデータを作成
1000.times do
  keys << SecureRandom.alphanumeric
end

1000.times do
  values << SecureRandom.base64(100)
end

# valueの中身がばらばらの比較
a = Hash.new
b = Hash.new
keys.each do |key|
  a[key] = values.sample
  b[key] = values.sample
end

puts a == b ? "match!!" : "unmatch..."

# valueの中身を同一にした比較
a = Hash.new
b = Hash.new
keys.each_with_index do |key, i|
  a[key] = values[i]
  b[key] = values[i]
end

puts a == b ? "match!!" : "unmatch..."

結果

$ >> ruby test.rb
unmatch...
match!!

ちゃんと比較してる模様、ちゃんと公式に書いてある通りだった。

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