Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How To Change A Character In All Documents (4)

DZone's Guide to

How To Change A Character In All Documents (4)

·
Free Resource
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


Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}