From: Bill Kelly Date: 2008-09-20T20:01:10+09:00 Subject: Re: [QUIZ] One-Liners Mashup (#177 again) From: "Sebastian Hungerecker" > > James Gray wrote: > > New puzzle: Provide a one-liner that can wrap a body of text at a > > requested maximum length. > > Wasn't that a question in the old one liner quiz? > Anyway (without looking it up): > text.gsub(/.{1,80}/,"\\0\n") > Or if you want to avoid breaking in the middle of words: > text.gsub(/(.{1,80})\s+/, "\\1\n") > (you'll have lines above 80 chars if there's a single word with > more than 80 characters). Indeed, I recall this from a previous ruby-talk thread... my solution was like your 2nd one, above.... However, I seem to recall someone had come up with an elegant regexp to actually wrap words *on-or-before* the boundary. (I remember being impressed. Wish I could recall the technique. :) > Next question: > Sort an array of words by the words' values where a word's value is the > sum of the values of its letters and a letter's value is its position in > the alphabet. So the value of "Hello" is 8+5+12+12+15. Here's my solution: >> %w(abc abb aba).sort_by{|w| w.upcase.split(//).inject(0){|n,c| n+(c[0] - ?@)} } => ["aba", "abb", "abc"] ...I just refereshed my email, and I see that Holger Mack has beat me to a reply. I didn't have a follow-up challenge ready, so I'll just issue this meta challenge instead: Look back over the set of one-liner challenges so far which have gone unanswered and pick one................. (As of this writing these include, Daniel Moore's "Print out a Serpinski carpet"; James Gray's "Provide a one-liner that can wrap a body of text at a requested maximum length." [assuming strict requirements on maximum length], and, Holger Mack's "Write a function per(n) which returns the periodicity of 1/n." Regards, Bill