From: Jeff Pritchard Date: 2006-06-28T10:51:37+09:00 Subject: Re: string manipulation I really like Alex's solution to this. As a newbie, I always attempt these "easy" things just to help me learn more of the language. In this case, I got stymied by what I consider to be a failure of Ruby's "least surprise" efforts. My solution involved reversing the string as Alex did, and then trying to use "each_with_index" on it to iterate through the characters. ('with index', so I could use index % 4 to place the dashes) I have come to understand that in this case, "each" doesn't mean "each character". Surprise! My question is, is String#scan(/./) the best way to convert a string into an array so that one could then use Array#each or Array#each_with_index to mess with the characters? It seems to work in irb, but I'm guessing there are some corner cases where the regexp would falter. Also seems more computationally intensive that should be necessary to just split it up into characters. Also, my first thought on a solution for this was to simply walk along the string and insert dashes where appropriate. Why isn't there a "String#insert(where,str)" method? Inserting substrings into strings seems like such a common thing to do. And finally, a question about Alex's gsub. I don't quite follow the "\\0-" syntax. It appears related to the group matching discussed on page 326 of pickaxe, but not quite. Clearly in the "\\0-" sequence we have the first slash escaping the second one, so it is effectively \0 plus the '-', in other words replace the four characters matched with the four characters plus a dash. What I don't get is how \0 outside of the pattern is giving us anything useful. Seems like it should be $1 instead, since it is outside of the regular expression being matched. But then, there aren't any parenthesis, so there is no group, so perhaps $1 doesn't apply either. Can someone offer some clarification? thanks, jp Alex Young wrote: > siva kumar wrote: >> How to add "-" between the numbers >> Eg: >> 123456789123456789 as 12-3456-7891-2345-6789 >> >> > irb(main):001:0> str = "123456789123456789" > => "123456789123456789" > irb(main):002:0> str.reverse.gsub(/..../, "\\0-").reverse > => "12-3456-7891-2345-6789" -- Posted via http://www.ruby-forum.com/.