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

jrs*_*tto 16 ruby string ruby-1.9

我写了一个快速的小应用程序,它利用代码与某些关键词的基本文件,替换为关键字的文件,并输出与替换关键字的新文件.

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

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

["\r\nDim RunningNormal_1 As Boolean", "\r\nDim RunningNormal_2 As Boolean", "\r\nDim RunningNormal_3 As Boolean"]
Run Code Online (Sandbox Code Playgroud)

代替:

Dim RunningNormal_1 As Boolean
Dim RunningNormal_2 As Boolean
Dim RunningNormal_3 As Boolean
Run Code Online (Sandbox Code Playgroud)

我使用替换的散列{"KEYWORD" => ["1","2","3"]}和替代的线的阵列.

我用这个块来完成更换:

resultingLibs.each do |x|
  libraryString.sub!(/(<REPEAT>(.*?)<\/REPEAT>)/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
Run Code Online (Sandbox Code Playgroud)

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

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

*我对Ruby缺乏经验

sep*_*p2k 29

是的,你正在调用to_s一串字符串.在1.8中相当于调用join,在1.9中它等同于调用inspect.

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