Yogi Yogi - 1 year ago 73
Ruby Question

Random replacement of a particular character in file (ruby)

I tried to find a simple solution to replace a particular character randomly within a file.

Unfortunately, my solution replaces all found characters and not just some of them.

file_names = ['users_controller.rb']

file_names.each do |file_name|
text = File.read(file_name)
new_contents = text.gsub(",", ";") #replaces , to ; (unfortunatly all and not just some)
puts new_contents
File.open(file_name, "w") {|file| file.puts new_contents }

I appreciate any help, thanks.

Answer Source

The question is not clear. If you want to replace some random occurrences of a particular (fixed) character (",") with a particular (fixed) character (";"), then do:

text.gsub(","){rand(2).zero? ? "," : ";"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download