From: Alex Gutteridge Date: 2007-09-07T13:16:33+09:00 Subject: Re: help me condence my code? On 7 Sep 2007, at 09:29, Simon Schuster wrote: > anyhow, the sloppy newbie code is as follows: > > f = File.read("phrases_no_extra.txt") > f = f.to_a > f = f.each { |x| x.chop! } > f.each_with_index { |x,y| # deletes the empty array items > if x.size == 0 > f.delete_at(y) > end > } > f.each_with_index { |x,y| # deleting all but the last (which is > spread of two lines) > if x.include? "]" # of his comments > f.delete_at(y) > end > } > f.each_with_index { |x,y| # yes, this is me unable to recall > how to do "or" hahaha. > if x.include? "[" > f.delete_at(y) > end > } > f.delete_at(-1) # random whitespace item at the end from > the last quote > > puts f[rand(f.size)] > The main problem is that you loop through the Array four separate times first to chop, then to remove empty lines and then twice to remove comments. There is no reason why you can't combine them. Perhaps this is a good example to learn how to use 'or', 'and' and 'not': f = [] IO.readlines("phrases_no_extra.txt").each do |l| l.chop! f << l if l.size != 0 and not (l.include?("]") or l.include?("[")) end puts f[rand(f.size)] Alex Gutteridge Bioinformatics Center Kyoto University