Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string % 4 -> what is that in ruby

In ruby % is used to format string.

str % arg → new_str

However I do not get

number = '/javascripts/cache/money.js'.bytes.sum % 4

in this commit https://github.com/rails/rails/commit/f6a6b51ae551b7f936e974cba3ad4b30422d6804

like image 221
Nick Vanderbilt Avatar asked Dec 21 '22 11:12

Nick Vanderbilt


2 Answers

It depends on the class of the object.

On a string, % behaves like so:

"Hello, %s" % ['world'] #=> "Hello, world"

Note that in Ruby 1.9.2, you can add names:

"Hello, %{name}" % {:name => "Nick"} #=> "Hello, Nick"

For more details, see the docs.

However, on an integer, it is the modulo function. See the Fixnum docs and the Numeric docs.

like image 156
Mark Thomas Avatar answered Dec 24 '22 01:12

Mark Thomas


I think this % is Integer modulo.

'/javascripts/cache/money.js'.bytes  returns an Enumerator

'/javascripts/cache/money.js'.bytes.sum   returns an Integer

'/javascripts/cache/money.js'.bytes.sum % 4   returns an Integer

They may have defined the sum method themselves, which may be the reason for the question?

like image 33
Ray Toal Avatar answered Dec 23 '22 23:12

Ray Toal