quote

def quote str
   '"' + str + '"'
end

の代わりに、

def quote str
   %w(" ").join(str)
end

を思いついたんだけど、いかがなものか? 主客の転倒というかなんというか。

def sandwich ingredient, bread
   [bread, bread].join(ingredient)
end

def quote str
   sandwich str, '"'
end

だろうか?

class String
   def sandwich bread
      [bread, bread].join(self)
   end
end

str = "tomato-cheese-lettuce-ham"
puts str.sandwich("|") #=> |tomato-cheese-lettuce-ham|

元々はこうだっけ?


追記:

class String
   def sandwich bread
      [bread, bread].join(self)
   end

   def quote(str='"', alt=nil)
      (alt ? self.gsub(Regexp.compile(Regexp.quote(str))){alt} : self).sandwich(str)
   end
end

id:rubyco さんのツッコミのエスケープも含めたらこうかな?

puts str.quote              #=> "key=%Q|val|"
puts str.quote("|")         #=> |key=%Q|val||
puts str.quote("|", '\|')   #=> |key=%Q\|val\||

クォート文字列が「"」で、代替文字列を指定したい時ややめんどいな。