is there a way to replace multiple strings in a single line of array using gsub.
here is the log file
13:29:00 (alex) OUT: "72500_2010_0F" abcd@S400532
13:31:12 (alex) IN: "72600_2010_0F" abnc@S403818
13:31:52 (alex) IN: "71200_2010_0F" osa@S400583
I would like to replace the below
(alex) with ""
OUT: with OUT
IN: with IN
"72500_2010_0F" with XYZ
"71200_2010_0F" with QWE
"72600_2010_0F" with UIO
The original file (log file) is put into array and I wanted to read each line in the array and perform gsub. Dont want to use Hash as its lil complicated -As being Ruby Beginner...& to Regex...
array1.each do |element|
i = element.gsub(/?????????/) [ What should go here]
array2.push(i)
end
I dint want to make changes to original array but push the modified lines into different array ie array2
What is the best & easy to understand code to do this? - Please help
Looking at String#sub it seems there are many ways to do what you want:
One approach can be to use a hash as second parameter
def cleansed_log_line(line) replacement_rules = { 'alex' => '', 'OUT: ' => 'OUT ', 'IN: ' => 'IN ' } matcher = /#{replacement_rules.keys.join('|')}/ line.gsub(matcher, replacement_rules) end
Another approach can be to to use block form
def cleansed_log_line(line) replacement_rules = { 'alex' => '', 'OUT: ' => 'OUT ', 'IN: ' => 'IN ' } matcher = /#{replacement_rules.keys.join('|')}/ line.gsub(matcher) do |match| replacement_rules[match] || match end end
Another not so good implementation
def cleansed_log_line(line) replacement_rules = { /alex/ => '', 'OUT: ' => 'OUT ', 'IN: ' => 'IN ' } replacement_rules.each do |match, replacement| line = line.gsub(match, replacement) end line end
Hashes and RegEx are nothing to worry about. This function can cleanse any line passed to it and would return a cleansed line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.