ruby String类:什么是"%"符号方法?

时间:2014-12-26 15:32:12

标签: ruby

在ruby(2.2.0)String class documentation中,第一个INSTANCE方法如下:

str % arg → new_str

Format—Uses str as a format specification, and returns the result of applying it to arg. (...)

提供的第一个例子是:

"%05d" % 123    #=> "00123"

按照说明工作。 好的,但没有'。' '%'不能成为一种方法,可以吗? 如果不是,那么反而是什么(以及为什么列在'实例方法'?)

1 个答案:

答案 0 :(得分:3)

这是语法糖。如果您愿意,可以使用.进行调用:

"%05d" % 123
# => "00123"

相当于:

"%05d".% 123
# => "00123"

一个类似的例子:

1 * 2 + 3
# => 5
(1.*(2)).+(3)
# => 5

第二种形式是有效的,但我们通常会选择第一种形式,因为它更清晰。