为方法添加别名会导致不同的对象吗?
def foo
"foo"
end
alias foo2 foo
puts "foo2: " + foo2.object_id.to_s
puts "foo: " + foo.object_id.to_s
在上面的示例中,我希望每个方法调用看到相同的 object_id 输出,因为它们引用相同的方法。 为什么我看到不同的 object_id? 当你在 Ruby 中给一个方法起别名时,别名不是指原始对象,而不是副本吗?
def foo
"foo"
end
alias foo2 foo
puts "foo2: " + foo2.object_id.to_s
puts "foo: " + foo.object_id.to_s
In the above example, I expected to see the same object_id output for each method call since they reference the same method. Why do I see different object_id's? When you alias a method in Ruby doesn't the alias refer to the original object, not a copy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
重新开始一个新的答案来回应您的各种评论。
在示例代码中,您调用该方法,而不是引用它。 您想要用来
实际获取方法本身,而不是调用它的结果。
另外,
object_id
并不是测试两个方法是否相同的正确方法,因为method(:foo)
每次都会返回一个新的 Method 对象。 打个比方,如果您打开同一个文件两次,即使底层文件相同,您也会有两个不同的文件句柄。 相反,我认为您想要:如果您尝试一下,您会看到返回
true
。Starting over with a new answer in response to your various comments.
In the example code, you are calling the method, not referencing it. You want to use
to actually get the method itself and not the result of calling it.
Also,
object_id
is not the right way to test if two methods are the same, becausemethod(:foo)
returns a new Method object each time. For an analogy that might make this clearer, if you opened the same file twice you would have two distinct file handles even though the underlying file was the same. Instead, I think you want:which, as you will see if you try it, returns
true
.您正在对
foo
返回的对象调用object_id
,该对象是在方法中创建的字符串,因此每次都会不同。 如果您只调用foo
两次,您会看到相同的结果。 它每次都会返回一个新字符串。 如果您想要一个常量字符串,请返回符号:foo
。除此之外,尽管它们现在共享相同的实现,但它们是不同的方法。 如果您覆盖
foo
以返回字符串“bar”,foo2
仍将继续返回“foo”。You're calling
object_id
on the object returned byfoo
, which is a string created in the method and thus will be different every time. You'd see the same results if you just calledfoo
twice. It returns a new string every time. If you want a constant string, return the symbol:foo
instead.Past that, even though they share the same implementation right now, they are different methods. If you override
foo
to return the string "bar",foo2
will still keep returning "foo".尝试:
获得您想要的效果。 “foo”是一个表达式,每次调用该函数时都会对其进行求值。 要了解这是为什么,请考虑一下您也可以这样写:
Try:
To get the effect you are wanting. "foo" is an expression and it gets evaluated each time the function is called. To see why this is, consider that you could just as well have written: