Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

String#%

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

Returns the result of formatting object into the format specifications contained in self (see Format Specifications):

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

If self contains multiple format specifications, object must be an array or hash containing the objects to be formatted:

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"

Related: see Converting to New String.

See also .try_convert #* .new #+ also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0