使用Ruby的Code Block创建一个Hash比较函数
在使用Ruby开发时,经常会遇到需要比较两个Hash对象的值的场合。代码类似如下:
Ruby代码- 1.x = Hash.new
- 2.x[:a] = 'x'
- 3.y = Hash.new
- 4.y[:a] = 'y'
- 5.
- 6.x.keys.each do |key|
- 7. if x[key] != y[key]
- 8. puts "find difference for key #{key}: x = #{x[key]}, y = #{y[key]}"
- 9. end
- 10.end
- 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便可以实现:
Ruby代码- 1.def diff(hash_a, hash_b)
- 2. hash_a.keys.each do |key|
- 3. if hash_a[key] != hash_b[key]
- 4. yield key
- 5. end
- 6. end
- 7.end
- 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的比较了,代码也干净许多,最重要的是逻辑可以复用:
Ruby代码- 1.x = Hash.new
- 2.x[:a] = 'a'
- 3.y = Hash.new
- 4.y[:a] = 'b'
- 5.
- 6.diff(x, y) do |key|
- 7. puts "find difference for key #{key}: x = #{x[key]}, y = #{y[key]}"
- 8.end
复制代码 |