Ruby 链接如何工作?
为什么你可以链接这个:
"Test".upcase.reverse.next.swapcase
但不能链接这个:
x = My_Class.new
x.a.b.c
哪里
class My_Class
def a
@b = 1
end
def b
@b = @b + 2
end
def c
@b = @b -72
end
end
Why can you chain this:
"Test".upcase.reverse.next.swapcase
but not this:
x = My_Class.new
x.a.b.c
where
class My_Class
def a
@b = 1
end
def b
@b = @b + 2
end
def c
@b = @b -72
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
upcase
、reverse
、next
和swapcase
方法都返回String
对象,并且所有这些方法用于...您猜对了,String
对象!当您调用一个方法时(通常是 99.9999%),它会返回一个对象。该对象具有定义在其上的方法,然后可以调用这些方法,这解释了为什么您可以这样做:
您甚至可以根据需要多次调用
reverse
:所有这些都是因为它返回相同类型的对象,即
String
对象!但您无法使用
MyClass
执行此操作:要使其正常工作,
a
方法必须返回一个具有b
的对象其上定义的方法。现在,似乎只有MyClass
的实例才会有这个。要使其正常工作,您可以将a
的返回值设置为对象本身,如下所示:据此推断,
b
方法还需要返回self< /code> 因为
c
方法仅在MyClass
类的实例上可用。在此示例中,c
返回什么并不重要,因为它是链的末尾。它可以返回 self,但不能。薛定谔的猫方法。在我们打开盒子之前没有人知道。The
upcase
,reverse
,next
andswapcase
methods all returnString
objects and all those methods are for... you guessed it,String
objects!When you call a method (more often than not, like 99.9999% of the time) it returns an object. This object has methods defined on it which can then be called which explains why you can do this:
You can even call
reverse
as many times as you like:All because it returns the same kind of object, a
String
object!But you can't do this with your
MyClass
:For that to work, the
a
method would have to return an object which has theb
method defined on it. Right now, that seems like only instances ofMyClass
would have that. To get this to work you could make the return value ofa
the object itself, like this:Extrapolating this, the
b
method would also need to returnself
as thec
method is available only on instances of theMyClass
class. It's not important whatc
returns in this example, because it's the end of the chain. It could returnself
, it could not. Schrödinger'scatmethod. Nobody knows until we open the box.作为对其他答案的支持,此代码:
...几乎与...完全相同
。...除了我上面的代码留下了指向中间结果的额外变量,而原始代码没有留下任何额外的引用。如果我们对您的代码执行此操作:
使用 Ruby 1.9 的
tap
方法,我们甚至可以使其更加明确:As support for other answers, this code:
...is almost exactly the same as...
....except that my code above has extra variables left over pointing to the intermediary results, whereas the original leaves no extra references around. If we do this with your code:
Using Ruby 1.9's
tap
method, we can even make this more explicit:函数中的最后一个表达式是其隐式返回值。如果你想链接这样的方法,你需要返回 self 。
例如,您的
a
方法当前返回1
。b
不是数字方法。您需要像这样修改它:The last expression in a function is its implicit return value. You need to return
self
if you want to chain methods like that.For example, your
a
method is currently returning1
.b
is not a method for numbers. You'll want to modify it like so: