如果在 Ruby 中一切都是对象,甚至数学运算符都是应用于对象的方法,当我写下:
puts "Hello world"
方法是puts,参数是“Hello world”,但是对象是什么?
最佳答案
放
要查找方法,您可以调用:
method(:puts)
#=> #<Method: Object(Kernel)#puts>
所以puts
是定义在Kernel
中的方法,对每个Object都可用。
内核#puts
puts "Hello world"
实际上是
self.puts( String.new("Hello world") )
self
是对象 main
.
所以 puts "hello world"
是:
- Kernel#puts方法调用
- 在
main
上 - 以字符串对象作为参数。
注意事项
注意如果执行
self.puts( String.new("Hello world") )
你会得到一个错误:
private method `puts' called for main:Object (NoMethodError)
因为每个内核方法都可用于每个对象,但作为私有(private)方法。你需要:
self.send(:puts, String.new("Hello world") )
测试
另一种检查方法是:
module Kernel
def my_puts(*args)
print "Calling Kernel#my_puts on #{self} with #{args}\n"
print "Now delegating to Kernel#puts on #{self} with #{args} :\n"
puts(*args)
end
end
my_puts "Hello world"
输出:
Calling Kernel#my_puts on main with ["Hello world"]
Now delegating to Kernel#puts on main with ["Hello world"] :
Hello world
看到了吗?一切都是对象,即使它可能看起来不像。
2+3
同理:2+3
实际上是 Integer(2).+( Integer(3) )
.
关于ruby - Ruby 的 "hello world"中的对象是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41919601/