ruby string percent method

原创文章,转载请注明来源并保留原文链接

Last week, when i checked a question in StackOverflow, i found an interesting thing. See the example below:

"%d hour %d minutes %d seconds" % [ 1, 20, 30 ]
# => "1 hour 20 minutes 30 seconds"

At first, i thought the percent % is just liked 11%3, so i looked into ruby-doc, i got my answer, % is nothing but a instance method of String

Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array or Hash containing the values to be substituted. See Kernel::sprintf for details of the format string.

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

"%-5s: %08x" % [ "ID", self.object_id ]  
#=> "ID: 200e14d6"

"foo = %{foo}" % { :foo => 'bar' }
#=> "foo = bar"

The syntax of a format sequence is follows.

%[flags][width][.precision]type

Kernel#sprintf

Leave a Reply

Your email address will not be published. Required fields are marked *