开发者

In Ruby how can the last method on a chain access the initial object

开发者 https://www.devze.com 2023-04-06 15:14 出处:网络
- EDIT, SOLVED - Ended up creating a method Object#rec to accomplish what I needed, this is the result:

- EDIT, SOLVED -

Ended up creating a method Object#rec to accomplish what I needed, this is the result:

#$l stores the last object on which Object#rec was called
$l=nil;class Object;def rec;$l=self;end;end

class String
    attr_accessor :ref
    alias_method :old_reverse, :reverse
    def reverse
        self.rec.old_reverse
    end
    def my_method
        $l.ref + ' ' + self
    end
end

a = "Hello"
b = "dlroW" ; b.ref = a

p b.reverse.my_method #=> Hello World

If anyone has a better way the question is still open.

- EDIT, SOLVED -


The problem:

I have a situation similar to this:

obj.method1.method2

where method1 returns something other than obj and I need method2 to access obj again as it holds a reference I need.


For example:

class String
    attr_accessor :ref
    def my_method(b)
        b.ref + ' ' + self
    end
end

a = "Hello"
b = "dlroW" ; b.ref = a

#I want my_method to access 'b.ref' without having to pass 'b'
p b.reverse.my_method(b) #=> Hello World

Alternative:

I know I could avoid having to pass b again if I used obj.my_method and my_method did both reversing(for the example) and accessing the reference, or like commented by the Tin Man have method1 change obj but return the origi开发者_开发百科nal obj, but what I want is to know if it's possible or not to accomplish the above.

Thanks in advance.


Sounds kind of like you're looking for Object.tap:

Yields x to the block, and then returns x. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

For your example, you might be able to use String's reverse! inside the tap to manipulate the object. For your application, manipulate the object as you desire inside tap, then the object will be passed on to your following method.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号