Alex LeDonne
9/6/2006 2:51:00 PM
On 8/31/06, Berger, Daniel <Daniel.Berger@qwest.com> wrote:
> > -----Original Message-----
> > From: list-bounce@example.com
> > [mailto:list-bounce@example.com] On Behalf Of Brian Nice
> > Sent: Thursday, August 31, 2006 8:39 AM
> > To: ruby-talk ML
> > Subject: splitting string to hash
> >
> >
> > I have a strings like the following:
> > s1- "[1] Hello [2] bye"
> > s2- "[1] Hello [2] bye [2:1] continue [2] more"
>
> Should that be "[2:2] more" ?
>
> > I want to convert them to hashes like
> > h1- {1 => "Hello", 2 => "bye"}
>
> arr = s1.split(/\s*?\[(.*?)\]\s*/)
> arr.delete("")
>
> h1 = Hash[*arr]
>
> I'm not actually sure why I get an empty string from the Array#split
> call. If someone can figure that out, you can get rid of the
> Array#delete call.
If you're capturing a group in your split pattern, and your pattern
matches the beginning of the string, you'll get the leading null field
in your array. By default, a trailing null field is suppressed; you
can get at it by setting the optional limit param to -1.
irb(main):001:0> "1234".split(/(\d)/)
=> ["", "1", "", "2", "", "3", "", "4"]
irb(main):002:0> "1234".split(/(\d)/, -1)
=> ["", "1", "", "2", "", "3", "", "4", ""]
-Alex