Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does % do in the following code?

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 }
like image 469
user1493194 Avatar asked Nov 26 '13 21:11

user1493194


1 Answers

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.

like image 72
tadman Avatar answered Oct 11 '22 13:10

tadman