-1

In the ruby (2.2.0) String class documentation, the very first INSTANCE method is the following:

str % arg → new_str

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

The first example provided is:

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

and works as stated. Ok, but without a '.' the '%' can't be a method, can it?
And if it is not, what is instead (and why is listed under the 'instance methods'?)

AgostinoX
  • 7,477
  • 20
  • 77
  • 137

1 Answers1

3

It's syntax sugar. You can call it with . if you want:

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

is equivalent to:

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

A similar example:

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

The second form is valid, but we usually choose the first form as it's clearer.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294