Skip to content

Instantly share code, notes, and snippets.

@joel
Created June 21, 2012 08:23
Show Gist options
  • Save joel/2964568 to your computer and use it in GitHub Desktop.
Save joel/2964568 to your computer and use it in GitHub Desktop.
Use Object Tap instead return
#!/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