Cs Webgrl wrote:
> better
> s = "string+var
> s.gsub('+','')
> s.strip!
> s.capitalize
> s => 'String Var'

(You need gsub! and capitalize! of course)

> Are there resources that explain why one is better than the other that
> also provides more best practices like this?

Methods like capitalize! work on the existing string buffer in memory. 
The non-bang methods create a whole new string, which involves work 
copying it, and then later garbage-collecting the original.

Most of the non-bang methods are implemented as a dup followed by 
calling the bang method on the copy. They're written in C, but are 
effectively like this:

class String
  def capitalize
    dup.capitalize!
  end

  def capitalize!
    # scan the string and modify it in place
  end
end

Of course, in most apps the original chained code you wrote will be just 
fine, and it's easy to write and understand. If you will be processing 
files which are hundreds of megabytes long then it may be worthwhile 
rewriting to the second form.

Other thoughts:

* for large files, process them in chunks or lines rather than reading 
them all in at once

* use block form when opening a file, to ensure it's closed as soon as 
you've finished with it

File.open("/path/to/file","rb") do |f|
  f.each_line do |line|
    ...
  end
end
-- 
Posted via http://www.ruby-forum.com/.