Project

General

Profile

Feature #8573

Add String#format method(not an alias of String#%)

Added by bozhidar (Bozhidar Batsov) almost 5 years ago. Updated 2 months ago.

Status:
Feedback
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:55682]

Description

I think it'd be great if String included a method similar to % that accepts variable number of arguments (like sprintf). This is trivial to implement as you're certainly aware.

Here's one implementation suggestion:

class String
def format(*args)
super(self, *(args.flatten))
end
end

This would make the new method behave both like sprintf/format and String#%. I think this minor improvement would definitely be in the spirit of making more programmers happy :-)

Here a bit more on the topic - http://batsov.com/articles/2013/06/27/the-elements-of-style-in-ruby-number-2-favor-sprintf-format-over-string-number-percent/

History

#1 [ruby-core:57527] Updated by nobu (Nobuyoshi Nakada) over 4 years ago

Do you mean this?

def format(*args)
  sprintf(self, *args)
end

or

def format(*args)
  self % args
end

#2 [ruby-core:57528] Updated by naruse (Yui NARUSE) over 4 years ago

  • Status changed from Open to Feedback
  • Priority changed from 3 to Normal
  • Target version changed from 2.1.0 to 2.6

Show concrete use case.

#3 Updated by naruse (Yui NARUSE) 6 months ago

  • Target version deleted (2.6)

#4 [ruby-core:86574] Updated by bozhidar (Bozhidar Batsov) 2 months ago

naruse (Yui NARUSE) wrote:

Show concrete use case.

How about simply:

"Hello, %s %s!".format("Mr.", "Bond")

#5 [ruby-core:86575] Updated by bozhidar (Bozhidar Batsov) 2 months ago

nobu (Nobuyoshi Nakada) wrote:

Do you mean this?

def format(*args)
  sprintf(self, *args)
end

or

def format(*args)
  self % args
end

I'd prefer something implemented in terms of sprintf.

#6 [ruby-core:86576] Updated by shyouhei (Shyouhei Urabe) 2 months ago

bozhidar (Bozhidar Batsov) wrote:

naruse (Yui NARUSE) wrote:

Show concrete use case.

How about simply:

"Hello, %s %s!".format("Mr.", "Bond")

That's too simple. What we need is how the requested feature improves the situation. What's wrong with the status-quo? and how is that relaxed using String#format?

Also available in: Atom PDF