DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

How To Change A Character In All Documents (4)

01.26.2011
| 1907 views |
  • submit to reddit
        Lets define a write() method in File class :
class File
 def self.write(name)
   data = yield
   self.open(name,"w") { |f| f.write( data ) }
 end
end

Now code with Dir[exp] ,  File.read(), File.write() :
Dir[ARGV[0]].each() do |file_name|
 file_content     = File.read(file_name)
 content_mofified = file_content.gsub(/a/,"@")
 File.write(file_name) { content_mofified }
end

Ruby -is- Block and meta-programming
without this, it's a python/php/...


Or, more functional :
Dir[ARGV[0]].each() { |file_name|  
  File.write(file_name) { File.read(file_name).gsub(/a/,"@") } 
}

This is the best form, because it don't use local variable
  ==> provable
  ==> threadable without danger


    

Comments

Snippets Manager replied on Fri, 2010/10/01 - 5:57am

Hello! First, i would like to apologise about my bad english. It is not my native. About your code. Yes, it is a shorter version, but when you learn, you need to understand, what is what, and a lot of people are lost, when they see code like that. I was too, when i was a beginer. So i decideded that every code i will post, will be expanded, that beginners will follow. Profesionals allready have knowledge to build it by their own.