在Ruby中,链上的最后一个方法如何访问初始对象
- 编辑,已解决-
最终创建了一个方法 Object#rec
来完成我所需要的,这就是结果:
#$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
如果有人有更好的方法,问题仍然存在。
- 编辑,已解决 -
问题:
我遇到了与此类似的情况:
obj.method1.method2
其中 method1
返回 obj
并且我需要 method2
再次访问 obj
因为它包含我需要的引用。
例如:
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
替代方案:
我知道如果我使用 obj.my_method
和,我可以避免再次传递 b
my_method
既进行了反转(例如)又访问了引用,或者像 the Tin Man
所评论的那样,将 method1
更改了 obj< /code> 但返回原始内容
obj
,但我想知道是否可以完成上述任务。
提前致谢。
- 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 original obj
, but what I want is to know if it's possible or not to accomplish the above.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来有点像您正在寻找
Object.tap
:
对于您的示例,您可以在
tap
内使用 String 的reverse!
来操作该对象。对于您的应用程序,在tap
中根据需要操作该对象,然后该对象将传递给您的以下方法。Sounds kind of like you're looking for
Object.tap
:For your example, you might be able to use String's
reverse!
inside thetap
to manipulate the object. For your application, manipulate the object as you desire insidetap
, then the object will be passed on to your following method.