Re: simple gsub question \' \` what?




On Mar 30, 2007, at 5:39 PM, Timothy Hunter wrote:

Dustin Anderson wrote:
Sorry for the simple question, I just can't figure this out after a
couple hours...

I need to parse a string:

string = column-1:block-0,block-2,block-1,block-3

and I need to extract everything before the : (colon) into one variable
(should end up like this:
string1 = column-1

and then the rest of the string (block-0,block-2,block-1,block3) into an
array...

I'd use two calls to split:

irb(main):001:0> string = 'column-1:block-0,block-2,block-1,block-3'
=> "column-1:block-0,block-2,block-1,block-3"
irb(main):002:0> string1, s = string.split(':')
=> ["column-1", "block-0,block-2,block-1,block-3"]
irb(main):003:0> string1
=> "column-1"
irb(main):004:0> string2 = s.split(',')
=> ["block-0", "block-2", "block-1", "block-3"]
irb(main):005:0>

You could probably turn that into a one-liner but that's just golfing.


Here's a bit of "live" code that does the same thing (plus .to_f on the elements before turning them into a Vector, but you can knock that part out yourself)

def add line
id, vals = line.split(/:\s*/, 2)
@labels << id
@data << Vector[*(vals.split(',').map {|v| v.to_f})]
end

Note that the second arg (2) to split is important if a ':' can occur anywhere in your block-N parts. Of course, you just need vals.split (',')

-Rob

Rob Biedenharn http://agileconsultingllc.com
Rob@xxxxxxxxxxxxxxxxxxxxxx



.



Relevant Pages

  • Re: Question about the split function
    ... First of all if you are trying to parse a file which is less than 10 MB u ... may use File.OpenText otherwise u should use StreamReader ... String[] stringData; ... > What I am trying to get is the stuff on the other side of the colon. ...
    (microsoft.public.dotnet.languages.csharp)
  • parsing pkcs#7 string
    ... I'm wondering if there is any class in CAPICOM that can parse the pkcs#7 ... I try to extract the certificates in the pkcs#7 but so far ...
    (microsoft.public.dotnet.security)
  • Re: Help with Regular expression
    ... > I am trying to write a regular expression to parse the string: ... > Am doing this to extract the values after the equals signand before ... > and I want the values stored in variables that are before the equals ...
    (microsoft.public.dotnet.framework)
  • Re: simple gsub question ` what?
    ... I need to parse a string: ... How can I use gsub to extract everything before the colon? ... I've looked at the documentation and just can't understand how to use ...
    (comp.lang.ruby)
  • RE: SQL Replace Function for Strings
    ... The solution is to find the position of the colon and than extract the string using this value from all values. ... For SQL: select KSName, SUBSTRING+1,1000) from job ...
    (microsoft.public.sqlserver.mseq)