Ruby: How to use the Merge method within Ruby Blocks


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #The Merge method is for Hashes only.
  2. h1 = { "a" => 111, "b" => 222 }
  3. h2 = { "b" => 333, "c" => 444 }
  4.  
  5. #Conflict resolution
  6. puts h1.merge(h2) { |key, old_value, new_value| old_value }
  7. puts h1.merge(h2) { |key, old_value, new_value| new_value }
  8.  
  9.  
  10. #Longhand
  11. puts h1.merge(h2) do |key, old_value, new_value|
  12. if old_value < new
  13. old_value
  14. else
  15. new_value
  16. end
  17. end
  18.  
  19. #Shorthand
  20. puts h1.merge(h2) { |k, o, n| o < n ? o : n }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.