Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created December 6, 2011 03:47
Show Gist options
  • Select an option

  • Save pasberth/1436624 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1436624 to your computer and use it in GitHub Desktop.
Object#tapはこう動いて欲しい!!!!!!
# -*- coding: utf-8 -*-
class Tapped < BasicObject
private *instance_methods # 全メソッドをmethod_missingへ転送する
def initialize obj, result=self
@obj = obj
@result = result
end
def method_missing f, *a, &b
res = @obj.send f, *a, &b
if @result.nil? then res else @result end
end
end
class Object
def tap result=self
if block_given?
res = yield self
if result.nil? then res else result end
else
Tapped.new self, result
end
end
end
a = [].tap do |a|
a << 1
a << 2
end
p a # => [1, 2]
a = [1, 2, 3].tap nil do |a|
a.reverse
end
p a # => [3, 2, 1]
obj = Object.new.tap.instance_eval do |obj|
@attr = "hello"
def attr
@attr
end
end
p obj.attr # => "hello"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment