From: Pete Yandell Date: 2007-09-07T14:22:31+09:00 Subject: Re: help me condence my code? Ok, I'm going to try break this down a bit more than the other answers. Simon Schuster wrote: > f = File.read("phrases_no_extra.txt") > f = f.to_a f = IO.readlines("phrases_no_extra.txt") > f = f.each { |x| x.chop! } Your "f =" at the start of this line does nothing. You'd be better off with either: f.each {|x| x.chop! } or I prefer: f.map! {|x| x.chop } > f.each_with_index { |x,y| # deletes the empty array items > if x.size == 0 > f.delete_at(y) > end > } For starters, I don't think each_with_index will be stable if you delete elements in the middle of the block, so this probably won't work the way you want it to. That and there's a convenient predicate for testing emptiness of strings. Much better would be: f.delete_if {|x| x.empty? } > 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.delete_if {|x| x.include("]") } > 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_if {|x| x.include("[") } > f.delete_at(-1) # random whitespace item at the end from the last quote f.pop > puts f[rand(f.size)] Nothing wrong with this line. :) So, putting that all together and cleaning up a bit: f = IO.readlines("phrases_no_extra.txt").map {|x| x.chop } f.delete_if {|x| x.empty? || x.include?("[") || x.include?("]") } f.pop puts f[rand(f.size)] That's pretty neat I think, but if you agree with Alex that looping over the array multiple times is a performance problem, then you should try something like: f = [] IO.each("phrases_no_extra.txt") do |x| x.chop! f << x unless x.empty? || x.include?("[") || x.include?("]") end f.pop puts f[rand(f.size)] (This is an improvement over Alex's solution in that it doesn't read the entire file into memory at once. Rather it steps over the file reading a line at a time and only adding the ones you need to your array.) Regards, Pete Yandell http://notahat.com/