From: teresa nuagen Date: 2011-10-17T07:02:46+09:00 Subject: Re: writing a poem backwards or in reverse order "Jesús Gabriel y Galán" wrote in post #1026900: > On Sun, Oct 16, 2011 at 8:08 PM, teresa nuagen > wrote: >> alright thanks for your advice and tips. I'm familiarizing myself with >> string and the order of words. Is array applied in this problem or i'm I >> only focusing on string? > > String#split returns an array of strings, so yes, you need to > understand arrays a bit. > An array is a container of objects, in which each element can be > accessed by index: > > array = [1,2,3,4] > array[0] --> 1 > array[1] --> 2 > etc. > > You can traverse an array using the code I showed above. > >> Can I have the poem in ruby and then change the order using separate >> programs or do I have to open the file through nano first and then in >> ruby? If so how do I open a nano file using ruby? My current file is >> "nano poem" to open it in ruby do I have to change it into a ".txt" >> file. How would I do that? > > I guess your idea is to have a text file containing the original poem, > and then using Ruby to reverse the order. You can create your file > using any text editor such as nano, vi, gedit or whatever (notepad on > Windows, for example). Save it with a name that you like, for example > poem, it doesn't need to end in .txt. Then you can read the contents > of the file using File.read, which returns a string with the contents > of the file. You can then split on "\n" (the end of line character) > and you get back an array of lines. Try this in irb: > > contents = File.read("poem") > puts contents > lines = contents.split("\n") > p lines > > and work from there. > > Jesus. I was able to figure out to program 1 and 3. This was the method I used using array. program 1: contents = File.read("poem") puts contents my_file = File.new("poem") line_array = my_file.readlines() line_array.reverse! line_array.each {|line| puts line} my_file.close program 3: contents = File.read("poem") puts contents my_file = File.new("poem") new_array = my_file.readlines() new_array.each do |line| puts line.reverse! end I'm trying to figure out how to incorporate the same method using an array for program 2, but I keep getting an error message. Is using a string the only way I can rearrange the order of words? Or am I tying both arrays and string in order to do it. -- Posted via http://www.ruby-forum.com/.