From: botp Date: 2011-10-17T16:31:56+09:00 Subject: Re: writing a poem backwards or in reverse order On Mon, Oct 17, 2011 at 1:02 PM, teresa nuagen wrote: > alright, so lets say this is an example: > > While moon sets > atop the trees, > leaves cling to rain. > > and I have to transform it into this: > rain. to cling leaves > trees, the atop > sets moon While s=<<-HERE While moon sets atop the trees, leaves cling to rain. HERE #=> "While moon sets\natop the trees,\nleaves cling to rain.\n" # let's split the string by newlines "\n" # the splitted components will be stored in an array a1=s.split("\n") #=> ["While moon sets", "atop the trees,", "leaves cling to rain."] # now, we arrange the array in reverse order # note, you can just use the same var a1, but i'd prefer we # use another var a2 so you can back track thru the vars a2=a1.reverse #=> ["leaves cling to rain.", "atop the trees,", "While moon sets"] # stop. let's see where we are. puts a2 leaves cling to rain. atop the trees, While moon sets #=> nil # good, we just need to arrange / reverse the words in the line # again, we just split the line by spaces where we get an array, # the call the reverse method for the array a3=a2.split.reverse NoMethodError: undefined method `split' for ["leaves cling to rain.", "atop the trees,", "While moon sets"]:Array from (irb):22 from /usr/local/bin/irb:12:in `
' # oops :) a3=a2.map{|x| x.split.reverse} #=> [["rain.", "to", "cling", "leaves"], ["trees,", "the", "atop"], ["sets", "moon", "While"]] # ok. i think we're near. we just need to join the words back a4=a3.map{|x| x.join(" ")} #=> ["rain. to cling leaves", "trees, the atop", "sets moon While"] # now, let's see puts a4 rain. to cling leaves trees, the atop sets moon While #=> nil # is that ok?