From: Xavier Noria Date: 2007-09-19T20:46:30+09:00 Subject: Re: Indenting strings - elegant alternatives? On Sep 19, 2007, at 1:13 PM, Ronald Fischer wrote: > Just in case someone would like to contribute ideas of elegant code: > > PROBLEM: > > Given a string of lines (for example, "abc\nde\nfgh\n") and a > number n, > produce a string of the same lines, but each line indented by n > spaces. > If the original string does NOT end in \n, it is OK (but not required) > to have it ending in \n in the result. > > Speed is not an issue; I'm mainly looking EITHER for compact/elegant > code in Core Ruby (noing well that elegance is a very subjective > criterium), OR for some library function which already has solved > this. > > Here is my own (pretty straightforward) solution to the problem: > > def indent(n,s) > (s.split.map {|x| (' '*n)+x}.join("\n"))+"\n" > end Another solution is: s.gsub(/^/, ' ' * n) -- fxn