[英]Cannot override to_s in irb
I defined a function :to_s in pry, but I am not able to call it. 我在pry中定义了一个函数:to_s,但是我无法调用它。 Where does this method go and how can I call it? 这种方法在哪里,我怎么称呼它?
pry(main)> def to_s
pry(main)* 'hello'
pry(main)* end
pry(main)> to_s
=> "main"
My ruby version is 2.1.2 我的ruby版本是2.1.2
when define a method in irb or pry, it goes to Object.instance_methods
当在irb或pry中定义方法时,它转到Object.instance_methods
[1] pry(main)> def to_s
[1] pry(main)* 'hello'
[1] pry(main)* end
=> :to_s
[2] pry(main)> def hello
[2] pry(main)* 'world'
[2] pry(main)* end
=> :hello
[4] pry(main)> Object.instance_methods(false)
=> [:pry, :__binding__, :to_s, :hello]
These new methods can be called in a new object. 可以在新对象中调用这些新方法。
[6] pry(main)> Object.new.to_s
=> "hello"
The reason I'm not able to call to_s in top-level is that main
is a special object which defined a #to_s
and #inspect
method. 我无法在顶层调用to_s的原因是main
是一个定义了#to_s
和#inspect
方法的特殊对象。
[5] pry(main)> singleton_class.instance_methods(false)
=> [:to_s, :inspect]
@Anthony's answer explains the context. @ Anthony的答案解释了背景。 To define your own to_s
at this level, you could do it this way: 要在此级别定义您自己的to_s
,您可以这样做:
pry(main)> to_s
=> "main"
pry(main)> def self.to_s
pry(main)* 'hello'
pry(main)* end
pry(main)> to_s
=> "hello"
You're actually at the top level Object class#to_s
method which as the docs states: 您实际上处于顶级Object class#to_s
方法,正如文档所述:
Returns a string representing obj. 返回表示obj的字符串。 The default to_s prints the object's class and an encoding of the object id. 默认的to_s打印对象的类和对象id的编码。 As a special case, the top-level object that is the initial execution context of Ruby programs returns “main”. 作为一种特殊情况,作为Ruby程序的初始执行上下文的顶级对象返回“main”。
Methods defined at the toplevel become private
instance methods of Object
. 在toplevel定义的方法成为Object
private
实例方法。
So, 所以,
def to_s; 'hello' end
is equivalent to 相当于
class Object; private def to_s; 'hello' end end
And message sends without an explicit receiver are implicitly sent to self
. 没有显式接收器的消息发送被隐式发送给self
。
So, 所以,
to_s
is equivalent to 相当于
self.to_s
At the top-level, self
is the nameless top-level object, usually called main
. 在顶层, self
是无名的顶级对象,通常称为main
。
Now, if any of the classes of main
override Object#to_s
, then the overridden version will be called. 现在,如果任何main
类覆盖Object#to_s
,则将调用被覆盖的版本。 And in fact, to_s
is overridden in the singleton class of main
: 而事实上, to_s
被重写的单例类的main
:
method(:to_s).owner
# => #<Class:#<Object:0x007fb5210c1c68>>
Another, admittedly verbose, way to accomplish what you're trying to do is to manipulate the "current" class, like so: 完成你要做的事情的另一种方法是,操作“当前”类,如下所示:
class << self
def to_s
"hello"
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.