Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

String#%

(::array[untyped] positional_args) -> ::String
(::hash[::Symbol, untyped] named_args) -> ::String
(untyped arg) -> ::String
string % object → new_string

Returns the result of formatting object into the format specification self (see Kernel#sprintf for formatting details):

Example
"%05d" % 123 # => "00123"

If self contains multiple substitutions, object must be an Array or Hash containing the values to be substituted:

Example
"%-5s: %016x" % [ "ID", self.object_id ] # => "ID   : 00002b054ec93168"
"foo = %{foo}" % {foo: 'bar'} # => "foo = bar"
"foo = %{foo}, baz = %{baz}" % {foo: 'bar', baz: 'bat'} # => "foo = bar, baz = bat"
See also .try_convert #* .new #+ also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0