Percent
The percent symbol (%
) flies under the radar, but it is a versatile and useful character throughout Ruby.
Modulo Operator
The most familiar use coming from any programming language is its use as the modulo operator.
10 % 3 # => 1
Percent Notation
The percent symbol is also used in a uniquely Ruby way to do a variety of conversions known as Percent Notation.
Here are some examples of percent notation:
> %<They say "I don't have to escape quotes!">
=> "They say \"I don't have to escape quotes!\""
> %q:Look, no interpolation #{true}:
=> "Look, no interpolation #{true}"
> statuses = %i[pending approved rejected]
=> [:pending, :approved, :rejected]
Head over to the Percent Notation page for a more in-depth explanation.
String Formatting
Though any class may choose to override the #%
method, the String
class does so in a uniquely useful way worth mentioning.
The String#%
method allows us to interpolate a string with a single value or values from an array or hash using these formatting specs ↗.
With a single value:
> count = 10
=> 10
> "I would like %s tacos" % count
=> "I would like 10 tacos"
With arrays:
statuses = [
['Active', 'Bob'],
['Inactive', 'Alice'],
['N/A', 'HAL9000']
]
=> [["Active", "Bob"], ["Inactive", "Alice"], ["N/A", "HAL9000"]]
statuses.each do |status|
puts "%-8s : %s" % status
end
Active : Bob
Inactive : Alice
N/A : HAL9000
With a hash:
> book = {title: "The Fifth Season", author: "N.K. Jemisin"}
=> {:title=>"The Fifth Season", :author=>"N.K. Jemisin"}
> template = "My book rec is %{title} by %{author}"
=> "My book rec is %{title} by %{author}"
> template % book
=> "My book rec is The Fifth Season by N.K. Jemisin"