Search code examples
rubystringtextprintftext-formatting

How to conditionally format strings in Ruby?


This is something that I have been trying to figure out for a while but cannot quite figure it out.

Let's say I have these four elements:

  • name = "Mark"
  • location = ""
  • time = Time.now
  • text - "foo"

And if I used str#% for formatting, like so: "%s was at the location \"%s\" around %s and said %s" % [name,location,time.to_s,text], how would I avoid the problem of blank spaces and orphaned words? (For example, "Mark was at the location "" around 2011-12-28T020500Z-0400 and said foo")

Are there any other techniques that I could use?


Solution

  • Just build the string piecemeal and assemble the results. You could easily cleanup the following if you had access to .blank? (I think it's blank?)

    parts = []
    parts << name if name && !name.empty?
    parts << "was" if name && !name.empty? && location && !location.empty?
    parts << %{at location "#{location}"} if location && !location.empty?
    parts << "around #{time}"
    parts << "and" if location && !location.empty? && text && !text.emtpy?
    parts << "said #{text}" if text && !text.empty?
    parts.join(" ")