如果Ruby受Smalltalk的影响很大,不知Ruby中是否有类似Smalltalk中的printNl
的等价方法?
我对在 Smalltalk 中的想法非常着迷,你实际上有一些东西,比如一个字符串,然后你将消息 printNl
(用于使用换行符打印)发送到字符串对象。它以 OOP 方式进行,而不是 p obj
或 puts obj
的过程方式。
我只找到了 Object
的 display
方法,它没有 displayNl
替代方法。 Ruby 中有吗?
只是为了好玩我做了以下,但我想知道如果它污染了 Object 类是否可能不好:
class Object
def displayNl
self.display
"\n".display
end
end
"hello world".displayNl
5.displayNl
3.14.displayNl
Time.now.displayNl
Time.displayNl
Fixnum.displayNl
[1,3,5].displayNl
{foo: "bar"}.displayNl
-----------------
$ ruby try.rb
hello world
5
3.14
2015-12-16 14:44:09 -0800
Time
Fixnum
[1, 3, 5]
{:foo=>"bar"}
最佳答案
I wonder if it may be not good if it contaminates the
Object
class
没错!为什么将自身打印到控制台是对象的责任?由控制台负责打印字符串不是更有意义吗?
这正是它在 Ruby 中的工作方式:IO#print
(和 IO#puts
)允许 IO
对象打印字符串给自己,#to_s
协议(protocol)允许任何对象将其自身表示为字符串。
Kernel#print
(和 Kernel#puts
、 Kernel#p
)只是一种方便的方法,基本上看起来像这样:
module Kernel
private def print(*args)
$>.print(*args)
end
end
$>
是默认输出流,在启动时它与 $stdout
和 STDOUT
相同, 但它可以重新分配。它是 IO
的实例。
IO#print
看起来像这样:
class IO
def print(*args)
args.map(&:to_s).each do |str|
some_internal_io_method_to_print_strings(str)
# in a C-based Ruby implementation probably calling fputs from the libc
end
end
end
因此,换句话说,Ruby 以“面向对象的方式”进行操作。 IO
对象知道如何打印字符串,#to_s
方法允许对象将自身表示为字符串。
换句话说:我认为 Object#display
一个错误。
您可能会注意到,在 YARV 中,它实际上是在 io.c
中定义的而不是 object.c
, 因此即使是作者似乎也同意此功能属于 IO
,而不是 Object
。
这是一个相当古老的方法,the oldest trace我能找到的是 this commit from January, 1999 ,似乎来自 version 1.3.1 release .这里,其实是defined in Kernel
, not Object
.
在此之前,跟踪在 CVS2SVN 转换的迷雾中丢失了。
关于ruby - 在 Ruby 中,是否有与 Smalltalk 中等效的 printNl 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34323633/