I wrote the code to query a txt file, and tried remove matched line like
as below but it not work as well, can someone help?
src.collect do |e|
if e=~/^(#)/
src.delete(e)
end
end
Yep. The collect method returns a copy of your source array, but
doesn’t modify it. OTOH, collect! does what you want. That being said,
I’d use reject! myself :
You can as well do this which is a tad shorter and probably also more
efficient than reading into a single String:
puts File.readlines(“./src.txt”).grep(/^[^#]/)
Only shorter because of the lack of join… which I do mostly out of
habit but also because puts is subject to the value of $, . Granted,
it doesn’t get modified much, but I prefer to know what is going to be
printed. Muscle memory. shrug
I doubt the readlines is more efficient as far as memory goes. 1
string + 1 array + N strings vs 1 array + M strings + 1 array + N
strings. As far as time? I dunno. I could measure but I doubt it makes
much difference in the grand scheme of things.
Only shorter because of the lack of join… which I do mostly out of
habit but also because puts is subject to the value of $, . Granted,
it doesn’t get modified much, but I prefer to know what is going to be
printed. Muscle memory. shrug
OTOH, if you globally set $, you intentionally do so and want all
output to use it.
I doubt the readlines is more efficient as far as memory goes. 1
string + 1 array + N strings vs 1 array + M strings + 1 array + N
strings. As far as time? I dunno. I could measure but I doubt it makes
much difference in the grand scheme of things.
I recall one occasion (I believe in one of Dave T.'s books) where
they could remedy a performance issue by going from String#<< to
Array#<<. I’d say the gain comes from the way mem is reallocated: in
the Array only Array memory is reallocated which is far less than
String mem when you have all in one String.
Of course, memory wise every solution that does not require the whole
file in mem at some point in time is more efficient and more robust
for large files.