Reputation: 343
I'm reading The "Rails 3 Way" and on page 39, it shows a code sample of the match :to =>
redirect method. In that method the following code exists. Whilst I know what modulo does with numbers, I'm unsure what the % is doing below because both path and params are clearly not numbers. If anyone can help me understand the use of % in this situation, I'd appreciate it.
proc { |params| path % params }
Upvotes: 5
Views: 113
Reputation: 211750
That's probably the String#%
method which works a lot like sprintf
does in other languages:
'%05d' % 10
# => "00010"
It can take either a single argument or an array:
'%.3f %s' % [ 10.341412, 'samples' ]
# => "10.341 samples"
Update: As Philip points out, this method also takes a hash:
'%{count} %{label}' % { count: 20, label: 'samples' }
# => "20 samples"
Of course, this is presuming that path
is a String. In Ruby you never really know for sure unless you carefully read the code. It's unlikely, but it could be %
meaning modulo.
The thing you can be sure of is it's calling method %
on path
.
Upvotes: 10
Reputation: 84453
It does string interpolation. In the simplest case, it's equivalent to:
"foo %s baz" % 'bar'
#=> "foo bar baz"
However, you can use more complex format specifiers to interpolate from Array or Hash objects too, such as the Rails params hash. See the String#% and Kernel#sprintf methods for details on how to construct a valid format specification.
Upvotes: 2