Re: splitting string to hash



William Crawford wrote:
Brian Nice wrote:
I have a strings like the following:
s1- "[1] Hello [2] bye"
s2- "[1] Hello [2] bye [2:1] continue [2] more"

I want to convert them to hashes like
h1- {1 => "Hello", 2 => "bye"}
h2- {1 => "Hello", 2 => "bye", "2:1" => "continue", "2:2" => more"}

Is there an easy Ruby way to do this?
Thanks for the help
Brian

Assuming that James is correct in that :2 is missing from the second
string, this works:

h2 = Hash[*s2.scan(/\[([^\[\]]+)\] (\w+)/).flatten]

(I'm starting to really like Ruby.)

In case that's not clear, scan uses a regex to provide an array of
2-element arrays from the text. Then flatten makes it into a single
array, then the * turns it into a list of just values, instead of an
array. Then Hash[] turns each 2 values into a hash.

Actually the original was correct - the second 2 should have a key of
2:2 even though it only appears in the original string as 2 (since it
follows a 2:1, it is assumed that any number after it would be 2:x. If
there was a 3:1 sometime later, then the next two would have a key of
3:2)

s2- "[1] Hello [2] bye [2:1] continue [2] more"

Thanks for the help
Brian

--
Posted via http://www.ruby-forum.com/.

.



Relevant Pages

  • Re: splitting string to hash
    ... Is there an easy Ruby way to do this? ... Assuming that James is correct in that:2 is missing from the second ... scan uses a regex to provide an array of ... Then Hash[] turns each 2 values into a hash. ...
    (comp.lang.ruby)
  • Re: Have you seen this error before?
    ... On Jun 10, 2004, at 12:56 PM, jason corbett wrote: ... Array if you want to walk it be index, hash if you want to walk it by ... James ...
    (perl.beginners)
  • Re: Mering an array of hashes
    ... And I would like the resulting array to look like: ... I'm sure there's an easy ruby way ... niceer without turning the data in to an array of rows as I do in first ...
    (comp.lang.ruby)
  • Duck Typed Concepts for Ruby (was Re: A use case for an ordered hash)
    ... An Sequencable mixin can be defined that implements all sorts of operations such as append, concat, splice, sort, etc. ... extending an instance of Array with Sorted if the array is known to be sorted. ... Now returning to the thread at hand we can see that the difference between the associative array and hash hierarchies is that the hash hierarchy depends upon Hashable keys. ...
    (comp.lang.ruby)
  • Re: Suggestions for double-hashing scheme
    ... >> The items that are being moved are the items in the hash table itself, ... >> which are of fixed size (they are in an array, ... > typedef struct { ... One "uchar" aka 'unsigned char' is plenty to hold a probe ...
    (comp.programming)