CLR String.Format in Ruby
December 8th, 2007
I love using String.Format instead of string concatenation in C#. It’s become one of my favorite functions. For those who don’t know C#, String.Format works like this:
String.Format("Hello, {0}, today's date is {1}!", "Joe",
DateTime.Now.ToShortDateString());
// <-- This will return "Hello, Joe, today's date is 12/8/2007!"
I’ve been coding in Ruby quite a bit lately. I couldn’t find a similar function, so I wrote my own:
class String
def self.format(format, *args)
index = 0
args.each do |arg|
format.sub!("{#{index}}", arg)
index = index + 1
end
format
end
end
The most beautiful part of this is I can still type String.format as I did before. The Ruby String.format actually redefines the String class, allowing it to define the class method I created. This feature is included in C# 3.0, known as Extension Methods (I’m not sure what they call it in Ruby). I guess I should mention it’s been in Ruby since the beginning.
Anyway, now in my Ruby classes, I can type:
String.format "Hello, {0}, today's date is {1}", "Joe", Date::today
# <-- Returns "Hello, Joe, today's date is 12/8/2007", just like before
If you would like to be able to use String.Format in Ruby, feel free to add this method to your Ruby project! Also, if you have any questions or comments, please feel free to leave them in the comments section!
Update [12/10/2007]: I have since learned that I can use variables directly in strings with Ruby, for example “Hello, ${name}, today’s date is ${Date::today}”. This is yet another example of where the beauty of Ruby makes a major feature in .NET completely obsolete. I’ll definitely be doing some refactoring to get rid of my String.format.
- Posted 4 months ago
- comments[0]
- Permalink
- Digg This!
