From: Simon Schuster [mailto:significants / gmail.com] 
# anyhow, the sloppy newbie code is as follows:

be gentle to yourself. it is not sloppy. in fact i find it readable and it clearly shows what the code is trying to do (wc may not be what you want to do)..  you can refactor it and put some tests as you go along.


# f = File.read("phrases_no_extra.txt")

on my case, i'd prefer that my programs do *not carry baggage of fixed static file names :) this way, my program does not depend on that particular file, and i can use any file i want. try ARGF.

# f = f.to_a

you can combine that w the above like

   f = File.read("phrases_no_extra.txt").to_a

or you can use readlines to accomplish both, like,

   f = File.readlines("phrases_no_extra.txt")


now, your original code makes many passes to array f. you can do it one pass, and since delete_if accepts a block, you can do it like,

f.delete_if do |x|
   x.sub!(/\[.*/,"")  # remove trailing comments
   x.sub!(/.*\].*/,"")  # remove leading comments, they span multi lines
   x.strip!           # remove leading/trailing whitespace
   x.empty?
end

note, we are also modifying the array as we move along..

thus combining w the above codes, you can futher condense it to 

f = File.readlines("phrases_no_extra.txt").delete_if do |x|
      x.sub!(/\[.*/,"")  # remove trailing comments
      x.sub!(/.*\].*/,"")  # remove leading comments, they span multi lines
      x.strip!           # remove leading/trailing whitespace
      x.empty?
    end

puts f[rand(f.size)]

you don't need the delete_at(-1) since (you said) it's a whitespace and will be taken care of by the code block.

using ARGF, you save chars, and your program is flexible, like

f = ARGF.to_a.delete_if do |x|
      x.sub!(/\[.*/,"")   # remove trailing comments
      x.sub!(/.*\].*/,"") # remove leading comments
      x.strip!            # remove leading/trailing whitespace
      x.empty?
    end
puts f[rand(f.size)]

_or_,  if you have fear of those ! methods (like me), you can do

f = ARGF.to_a.delete_if do |x|
      x.replace x.sub(/\[.*/,"").sub(/.*\].*/,"").strip
      x.empty?
    end
puts f[rand(f.size)]

kind regards -botp