From: Phillip Gawlowski Date: 2008-04-09T11:33:13+09:00 Subject: Re: output of a method to file? -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Zoe Phoenix wrote: | I think I understand what you're saying, but I'm not quite sure how to | apply it... Let me show you an example: irb(main):001:0> array = ["a","b","c","d","e"] => ["a", "b", "c", "d", "e"] irb(main):002:0> array.each_with_index do |item, index| irb(main):003:1* puts item if index % 3 == 0 irb(main):004:1> end a d => ["a", "b", "c", "d", "e"] In this example, only the elements at an index that can be divided by 3 without a problem are printed. You can achieve a similar effect with a counter, for example. (My idea to use modulo was a bit off, sorry about that). Translated to your problem: saving.rb: c_list = [ ~ 'Boston', ~ 'Nashville', ~ 'San Francisco', ~ 'Houston', ~ 'Portland', ~ 'Atlanta', ~ 'Chicago', ~ 'Indianapolis', ~ 'Charleston' ~ ] counter = 1 temp_array = [] c_list.each_with_index do |item,index| ~ temp_array.push "|| " if index % 3 == 0 ~ temp_array.push "#{item} " ~ temp_array.push "pets ||" ~ temp_array.push "\n" if counter % 3 == 0 ~ counter +=1 end puts 'File completed. Save as..?' save_as = gets.chomp File.open("c:/rubyfiles/citylist-#{save_as}.txt","w") do |f| ~ f.write temp_array end What am I doing here (this is a very naive implementation, nothing fancy, but it does what it is supposed to do)? First, I create the array of cities (you can get fancy later on, and read it from a file, too). Then, I create a counter to help me later on, as well as an empty array. After that, I iterate over the c_list array with the help of the each_with_index method. Now the fun starts: temp_array.push "|| " if index % 3 == 0 This only gets done, in the case that I can divide the index by 3 without a remainder. This works with 0, so I get the "|| " part. temp_array.push "#{item} " This uses Ruby's String interpolation to create, for example, "Boston ". String interpolation allows you to execute Ruby code within Strings, roughly speaking. You can test that by doing puts "#{Time.now}" in irb, for example. temp_array.push "\n" if counter % 3 == 0 This pushes the newline character into the array for file output, in the case that the counter variable I introduced earlier can be divided by 3 without a remainder. This should give you at least a starting point, in case I missed what you wanted. File block you already know. :) HTH, - -- Phillip Gawlowski Twitter: twitter.com/cynicalryan ~ - You know you've been hacking too long when... ...you begin to think in nested IF-THEN-ELSE clauses that would make a bureaucrat get lost. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkf8Ku8ACgkQbtAgaoJTgL+wMwCdEFdqJL6WyzUsNvZWTBjjc8Hh cqEAn2xcrv7D4uUwuMyc8GwvtptoYdbG =c3il -----END PGP SIGNATURE-----