Ruby 1.9 Array.to_s的行为有何不同?

我写了一个快速的小应用程序,它采用一些代码的基本文件和一些关键字,一个替换关键字的文件,并输出一个替换关键字的新文件。

当我使用Ruby 1.8时,我的输出看起来很好。 现在使用Ruby 1.9时,我替换的代码中包含换行符而不是换行符。

例如,我看到类似的东西:

["\r\nDim RunningNormal_1 As Boolean", "\r\nDim RunningNormal_2 As Boolean", "\r\nDim RunningNormal_3 As Boolean"] 

代替:

 Dim RunningNormal_1 As Boolean Dim RunningNormal_2 As Boolean Dim RunningNormal_3 As Boolean 

我使用替换哈希{“KEYWORD”=> [“1”,“2”,“3”]}和替换行的数组。

我用这个块完成更换:

 resultingLibs.each do |x| libraryString.sub!(/((.*?))/im) do |match| x.each do |individual| individual.to_s end end end #for each resulting group of the repeatable pattern, # #Write out the resulting libs to a combined string 

我的预感是我打印出数组而不是数组中的字符串。 有关修复的任何建议。 当我使用puts调试和打印我替换的字符串时,输出看起来是正确的。 当我使用to_s方法(这是我的应用程序将输出写入输出文件的方式)时,我的输出看起来不对。

修复会很好,但我真正想知道的是Ruby 1.8和1.9之间的变化导致了这种行为。 to_s方法在Ruby 1.9中以某种方式改变了吗?

*我对Ruby缺乏经验

是的,你在一个字符串数组上调用to_s 。 在1.8中相当于调用join ,在1.9中它等同于调用inspect

要在1.8和1.9中获得所需的行为,请调用join而不是to_s

请看这里 ,在Array

 Array#to_s is equivalent to Array#inspect [1,2,3,4].to_s # => "[1, 2, 3, 4]" instead of RUBY_VERSION # => "1.8.5" [1,2,3,4].to_s # => "1234"