Ruby 1.9 Array.to_s 的行为不同吗? [英] Ruby 1.9 Array.to_s behaves differently?

查看:21
本文介绍了Ruby 1.9 Array.to_s 的行为不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个快速的小应用程序,它采用带有一些关键字的基本代码文件、一个关键字替换文件,然后输出一个替换了关键字的新文件.

i wrote a quick little application that takes a base file of code with some keywords, a file of replacements for the keywords, and outputs a new file with the keywords replaced.

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

When i was using Ruby 1.8, my outputs would look fine. Now when using Ruby 1.9, my replaced code has the newline characters in it instead of line feeds.

例如,我看到类似:

["\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"]} 和替换行的数组.

i use a hash of replacements {"KEYWORD"=>["1","2","3"]} and an array of the replaced lines.

我用这个块来完成替换:

i use this block to finish the replacement:

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

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

My hunch is that i'm printing out the array instead of the strings within the array. Any suggestions on a fix. When i debug and print my replaced string using puts, the output looks correct. When i use the to_s method (which is how my app writes the output to the output file), my output looks wrong.

修复会很好,但我真正想知道的是 Ruby 1.8 和 1.9 之间发生了什么变化导致了这种行为.Ruby 1.9 中的 to_s 方法是否发生了某种变化?

A fix would be nice, but what i really want to know is what changed between Ruby 1.8 and 1.9 that causes this behavior. Has the to_s method changed somehow in Ruby 1.9?

*我对 Ruby 缺乏经验

*i'm inexperienced in Ruby

推荐答案

是的,您正在对字符串数组调用 to_s.在1.8中相当于调用join,在1.9中相当于调用inspect.

Yes, you're calling to_s on an array of strings. In 1.8 that is equivalent to calling join, in 1.9 it is equivalent to calling inspect.

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

To get the behavior you want in both 1.8 and 1.9, call join instead of to_s.

这篇关于Ruby 1.9 Array.to_s 的行为不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆