读书人

Ruby中这两个实现字符串替换的方法有何

发布时间: 2012-03-29 12:53:12 作者: rapoo

Ruby中这两个实现字符串替换的方法有何不同?为什么用FOR循环会报错?
第一个:用each实现的字符替换函数如下

Perl code
 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


第二个:用for循环实现的
Perl code
  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


第二个方法报错
Perl code
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


这是为什么呢?怎么解决?请高手帮忙!

[解决办法]
又测试了下,是因为你的Array类型数据越界了
arr的数据最大是arr[length-1]
arr[length]是Nil,而NilClass是没有index方法,所以报错了。

读书人网 >Ruby Rails

热点推荐