【问题标题】:ruby String class: what is the "%" symbol a method?ruby String 类:“%”符号是什么方法?
【发布时间】:2015-02-23 20:56:57
【问题描述】:

在 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"

并按说明工作。 好的,但没有“。” '%' 不能是方法,可以吗?
如果不是,取而代之的是什么(以及为什么在“实例方法”下列出?)

【问题讨论】:

  • 因为它是一个实例方法。 stackoverflow.com/a/3331974/438992 Ruby 有很多语法糖。同样的方式你可以覆盖其他操作符。
  • 它是一个类似于==+my_prop=的方法...

标签: ruby


【解决方案1】:

这是语法糖。如果需要,可以使用. 调用它:

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

相当于:

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

类似的例子:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2011-04-18
    • 2011-05-05
    • 1970-01-01
    • 2023-04-08
    • 2011-09-14
    • 1970-01-01
    相关资源
    最近更新 更多