Ruby中这两个实现字符串替换的方法有何不同?为什么用FOR循环会报错?
第一个:用each实现的字符替换函数如下
def findreplace(str,str1)
file=File.open("c:\\test.rb", 'r+')
arr=file.readlines
arr.each do |x|
y= x.index(str)
x.gsub!(str,str1)
puts arr unless y==nil
end
end
def findreplace2(str,str1)
#str='unless'
file = File.open("c:\\test.rb", 'r+')
arr = file.readlines
for i in 1..arr.length do
x = arr[i].index(str)
if x != nil
arr[i].gsub!(str, str1)
puts arr
end
end
end
C:\Documents and Settings\hongk\My Documents\NetBeansProjects\RubyCheatApplication\lib\main.rb:57:in `findreplace2': undefined method `index' for nil:NilClass (NoMethodError)
from C:\Documents and Settings\hongk\My Documents\NetBeansProjects\RubyCheatApplication\lib\main.rb:56:in `each'
from C:\Documents and Settings\hongk\My Documents\NetBeansProjects\RubyCheatApplication\lib\main.rb:56:in `findreplace2'
from C:\Documents and Settings\hongk\My Documents\NetBeansProjects\RubyCheatApplication\lib\main.rb:64