From: Thomas Hurst Date: 2003-06-23T18:04:00+09:00 Subject: Re: String#decorate * Martin DeMello (martindemello@yahoo.com) wrote: > When chaining methods, it'd be neat to have something that was passed > in the string and returned a 'decorated' version, e.g. > > pp = ary.join(",").decorate {|s| "[#{s}]"} You mean, equivilent to: s = ary.join(", ") pp = "[#{s}]" Which you would probably be better off writing as: pp = "[#{ary.join(', ')}]" And of course if you want the other way around: pp = ary.map { |s| "[#{s}]" }.join(", ") If you enjoy playing with blocks, you can do: pp = ary.join(", ").map { |s| "[#{s}]" }.to_s Perhaps setting $/ beforehand if you're going to be dealing with newlines. > attrib = title.capitalize.decorate {|t| "\t -- #{author[t]},\"#{t}\""} attrib = "\t -- #{author[t = title.capitalize]},\"#{t}\"" > (n*100).to_s.decorate {|p| "#{p}% done"} This makes about as much sense as an .interpolate method: "#{(n*100)}% done" > Not quite an RCR (it's trivially implementable anyway) - just wanted > to see what people thought of the idea, and in particular if anyone > had nicer names to suggest. Maybe uses for it can be found more generally -- in a generic "perform this block on myself" method? def Object.perform yield self end t = title.capitalize.perform { |t| "\t -- #{author[t]}, \"#{t}\"" } Or more likely: t = books.genre[genre].first.perform { |b| "#{b.title.capitalize}: #{b.author}" } But you're still basically replacing "b = " with " { |b| }" and adding some overhead for the block. Can you think of anything more worthwhile? The best I can come up with is: titleFormatter = proc { |b| "#{b.title.capitalize}: #{b.author}" } t = books.genre[genre].first.perform(titleFormatter) But that's just an inverted (and longer) way of doing: t = titleFormatter.call(books.genre[genre].first) I'm still not seeing much point :) -- Thomas 'Freaky' Hurst - freaky@aagh.net - http://www.aagh.net/