From: Dan __ Date: 2008-06-02T02:59:58+09:00 Subject: Re: Remove Parts of a String Eric I. wrote: > On Jun 1, 11:33�am, Dan __ wrote: >> Thanks very much Stefano :) �Thats exactly what I wanted, and it works >> great :) >> -- >> Posted viahttp://www.ruby-forum.com/. > > Hi Dan, > > You're the expert in your the domain, and I obviously don't understand > the larger picture. But the idea of getting access to the data after > the colons at a later stage using indexing into the original string > sounds unnecessarily complex. So here's another approach. > > If you run this, you'll see what you get at every step. > > ==== > > s = "12343:3,73820:1,183874:8" > > # break it up into an array of arrays of strings > a = s.split(',').map { |v| v.split(':') } > p a > > # now you can do lots of > things > > # just want the numbers before the > colons? > b1 = a.map { |v| v.first } > p b1 > > # want them as integers rather than > strings? > b2 = a.map { |v| v.first.to_i } > p b2 > > # want it as a string w/ commas? this seems to be part of your > original request > b3 = a.map { |v| v.first }.join(',') > p b3 > > # want to regenerate the original > string? > b4 = a.map { |v| v.join(':') }.join(',') > p b4 > > ==== > > Maybe (or maybe not) that's helpful.... > > Eric Hi Eric, thanks for the reply :) Your solution seems great for more complex data uses. However, I'm using this as part of a simple page-rating system in a Rails application right now. Basically, the number before the colon is the ID of a page that has been rated, and the number after the colon is the rating. The entire string stores every page and rating the user has ever given. So by splitting the string, and only looking at the number before the colon, I can compare the ID of the current page to the IDs of the pages the user has rated, and then display the rating they've given. It seems to me that both yours and Stephano's solutions are equally simple for what I'm using them for. If I had need to expand to a more complex system, I'd definitely use yours. I'm fairly positive that my use for the data won't expand beyond what it is now, and I've already got Stephano's solution implemented, so I'm gonna stick with that one ;) Thanks very much for offering your solution to the problem though :) -- Posted via http://www.ruby-forum.com/.