How do i use gsub?

Hi, i’m trying to open and edit a text document using regular expression
in Ruby, this is my code:

encoding: utf-8

#!/usr/bin/ruby

afile = File.new(“ex2.txt”, “r+”)
if afile
contents = afile.gsub(/[aeiou]/, ‘*’)
else puts “unable to open file”
end
puts contents

but when i run this, it comes up with an error message saying
"Testing.rb:6:in ‘’: undefined method ‘gsub’ for #<File:ex2.txt>
"

it seems to have a problem with gsub, however if i use this code
instead:

encoding: utf-8

#!/usr/bin/ruby

afile = File.new(“ex2.txt”, “r+”)
if afile
contents = “hello”.gsub(/[aeiou]/, ‘*’)
else puts “unable to open file”
end
puts contents

it works fine.
any ideas?
Thanks

Hi rebekahjp,

gsub is a method of the String object. In the first example, you’re
trying to call the gsub method on afile, which is a File object.
There’s no gsub method for the File object.

It works in the second example you listed because you are explicitly
calling gsub on the “hello” string. Since “hello” is a String object,
it is successful.

You should try reading a line of the file into the contents variable,
and then calling gsub on that.

I’m new to Ruby as well, but I hope that helps.

I hope it is usefull for you @rebekah

encoding: utf-8

!/usr/bin/ruby

original_contents = []
f = File.open(“filename.txt”, “r”)
f.each_line do |line|
original_contents << line.gsub(/[aeiou]/,’*’)
end
f.close

puts original_contents

puts “Happy Hacking with Ruby…!!!”

Thank you so much both of you! i’m very new to ruby and that’s solved a
big problem, thank you :slight_smile:

ah dont worry i’ve sorted it, i needed “new_file.puts” instead of
“new_file.write”

Thanks :slight_smile:

@sai_c

i added this code onto the end to save it to and output file:

new_file = File.new(“output.txt”, “r+”)
new_file.write(original_contents)
new_file.close

but in output it shows the array parenthesis and “\n” like so:

[“gfjrgjrpsghrjg\n”, “fdjgd\n", "jfdg**\n”, “f*d**p\n”, " *"]

How would i get the text out of an array and as normal text on multiple
lines?

Thanks