I'm reading a table from a MySQL database and then processing it row by
row, stripping each line of certain characters ([, ], " and comma)
before writing it to a file. The code is running without errors, but
it's not stripping any of the characters as I would expect.
Here's the code:
@bad_chars = ',"'
con = Mysql.new 'localhost', 'root', 'menagerie', 'haiku_archive'
rs = con.query("SELECT * FROM archive_2012")
n_rows = rs.num_rows
file = File.open("archive.html", "a")
line = rs.fetch_row.to_s
Executing the code results in an "archive.html" file with all of the
"stripped" characters still intact. Am I invoking the gsub method
incorrectly? Thanks in advance for any help.
I did read and attempt to implement every suggestion made, but
admittedly I'm new to Ruby and will make newbie mistakes (like mixing up
gsub and gsub!). I started out as a FORTRAN developer back in the early
80s but have been a Sys Admin since the early 90s, and am still trying
to wrap my mind around object-oriented programming.
Yes, my mistake, i was looking for that exact string instead of the
group. It should be this: /[\["\],]/
/ Start Regex
[ Start group
\ Escape next character
[ look for open square bracket
" Look for double quotes
\ Escape next character
] Look for close square bracket
, Look for comma
] End group
/ End Regex
Thanks once again to everyone for their suggestions.
It would be even better if you'd actually read them. :-/
What's the purpose of the "begin-end", by the way? This is not Pascal. A
"begin-end" block only makes sense in combination with "rescue" or
"ensure". Re-opening the file for every single row also doesn't really
make sense. Either open the file *before* the loop or collect the row
strings and then write them all at once.
File.open("archive.html", "a") do |file|
# I'm sure there's a better method for this, something like "each_row"
file << rs.fetch_row.to_s.delete('",')
it did not work, because his regular expression is describing a different pattern than you want: The \["\], looks for a [ (must be escaped in the regular expression, because it is a character with special meaning), followed by a ", followed by a ] (as with [), followed by a ,. His regular expression worked in his case, because he had ["], in his string. You want, as far as I can tell, remove all occurrences of those characters.
The regular expression you want is similar: /[\[\]",]/
If you don't know what this does, here's an explanation: The [ denotes the beginning of a set, and the ] ends it. The set matches to any character inside of it, but only one (because I did not write a quantifier like * or + after it).
So, this works:
"A[Aaaaa, \"aa".gsub( /[\[\]",]/, '' ) # => "AAaaaa aaa"
Alternatively, you could describe what you want with the regular expression /\[|\]|"|,/ since the pipe in regular expressions can be read as "or".
(Tested in Ruby 1.9.3p286; I don't know from the top of my head if the behavior would be any different in 1.8)