在使用Ruby開發時,常常會遇到須要比較兩個Hash對象的值的場合。代碼相似以下:
x = Hash.new
x[:a] = 'x'
y = Hash.new
y[:a] = 'y'
x.keys.each do |key|
if x[key] != y[key]
puts "find difference for key #{key}: x = #{x[key]}, y = #{y[key]}"
end
end
這樣寫代碼當然能夠,可是代碼顯得有些零亂,另外這種比較邏輯常常須要複用,能不能把它封裝在一個函數當中呢?答案是確定的,使用Ruby提供的yield即可以實現:
def diff(hash_a, hash_b)
hash_a.keys.each do |key|
if hash_a[key] != hash_b[key]
yield key
end
end
end
使用上面的函數就能夠進行Hash的比較了,代碼也乾淨許多,最重要的是邏輯能夠複用:
x = Hash.new
x[:a] = 'a'
y = Hash.new
y[:a] = 'b'
diff(x, y) do |key|
puts "find difference for key #{key}: x = #{x[key]}, y = #{y[key]}"
end