Created
June 21, 2012 08:23
-
-
Save joel/2964568 to your computer and use it in GitHub Desktop.
Use Object Tap instead return
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# http://blog.rubybestpractices.com/posts/gregory/011-tap-that-hash.html | |
# http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-tap | |
class TestingObjectTap | |
def legacy | |
results = {} | |
[:x, :y, :z].each do |letter| | |
results[letter] = rand(100) | |
end | |
results | |
end | |
def smart | |
returning({}) do |results| | |
[:x, :y, :z].each do |letter| | |
results[letter] = rand(100) | |
end | |
end | |
end | |
def sexy | |
{}.tap do |results| | |
[:x, :y, :z].each do |letter| | |
results[letter] = rand(100) | |
end | |
end | |
end | |
private | |
def returning(obj) | |
yield(obj) | |
obj | |
end | |
end | |
begin | |
object = TestingObjectTap.new | |
puts object.legacy | |
puts object.smart | |
puts object.sexy | |
end | |
# ruby object_tap.rb | |
# {:x=>74, :y=>90, :z=>42} | |
# {:x=>26, :y=>81, :z=>52} | |
# {:x=>85, :y=>13, :z=>24} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment