Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

string - Ruby 1.9 Array.to_s behaves differently?

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:

["
Dim RunningNormal_1 As Boolean", "
Dim RunningNormal_2 As Boolean", "
Dim 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...