Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created August 22, 2014 08:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/a9b12a7a3db9f9ca11ba to your computer and use it in GitHub Desktop.
Save Integralist/a9b12a7a3db9f9ca11ba to your computer and use it in GitHub Desktop.
Ruby string formatting functionality (like PHP's sprintf)
"foo-%s-baz" % "bar" # => "foo-bar-baz"
"foo-%s-baz" % 123 # => "foo-123-baz"
@stevenjack
Copy link

Me likey too

@kenoir
Copy link

kenoir commented Aug 22, 2014

"foo-%s-bar-%s" % ["hey", " you"]
"foo-%s-bar-%s,%d" % ["hey", " you" ,3]

@kenoir
Copy link

kenoir commented Aug 22, 2014

Further:

"foo-%s,%s" % Array.new(2) { |i| i + 1}

@kenoir
Copy link

kenoir commented Aug 22, 2014

Also:

"foo = %{foo}" % { :foo => 'bar' } 

From: http://www.ruby-doc.org/core-2.1.2/String.html

@ahmedofali
Copy link

ahmedofali commented Dec 4, 2019

def sprintf( text, *args )
  args.each do |arg|
    text['%s'] = arg
  end

  return text
end

puts sprintf( "ahmed %s work %s", "ali", "home" )``

Return

ahmed ali work home

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment