Ruby 1.9 Array.to_s behaves differently?

浪子不回头ぞ 提交于 2019-11-26 09:56:08

问题


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.

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.

For example, i see something like:

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

instead of:

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

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

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.

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?

*i\'m inexperienced in Ruby


回答1:


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.

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




回答2:


Please see here, under 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"


来源:https://stackoverflow.com/questions/3960392/ruby-1-9-array-to-s-behaves-differently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!