Hi all!
I'm testing the functionality of sprintf and I know that I can use it in
two way:
sprintf("%.3f", "1.2345")
=> "1.234"
Although it works the way you did it, that should have read
sprintf("%.3f", 1.2345)
IOW, it's a float format and not a string format.
Or
"%.3f" % "1.2345"
=> "1.234"
Same here:
"%.3f" % 1.2345
Actually you can do
irb(main):001:0> "%3d %04d" % [1,2]
=> " 1 0002"
i.e. work with multiple arguments. But for that I prefer (s)printf.
In the second example, what does mean the percent symbol (%) between
"%.3f" and "1.2345"? It means apply format string "%.3f" to string
"1.2345"? What I want to know is, the percent symbol is limited to
sprintf or it has a more general use in ruby?
% is an operator and is implemented / overloaded for several classes. The most commonly used is probably modulus operation for Fixnums.
irb(main):003:0> 10 % 3
=> 1
I've searched on the ruby pickaxe and several other ruby books but I
haven't found anything on the % alone, obviously there are many use of
that combined with option (array: %w, string: %q,%Q, regexp: %r, ...).
That's a completely different story, here % I would not call "operator" because it is not runtime effective. This occurrence of the percent sign is evaluated at compile time, more precisely during parsing. All these are convenience syntaxes to more easily express certain literals. For example, if you have a regular expression containing forward slashes the %r form is much easier on the eye:
%r{/+} vs. /\/+/
Kind regards
robert
···
On 28.04.2008 21:50, Toki Toki wrote: