tags:

views:

613

answers:

5

I've got a string

Purchases 10384839,Purchases 10293900,Purchases 20101024

Can anyone help me with parsing this? I tried using StringScanner but I'm sort of unfamiliar with regular expressions (not very much practice).

If I could separate it into

myarray[0] = {type => "Purchases", id="10384839"}
myarray[1] = {type => "Purchases", id="10293900"}
myarray[2] = {type => "Purchases", id="20101024"}

That'd be awesome!

+8  A: 

You could do it with a regexp, or just do it in Ruby:

myarray = str.split(",").map { |el| 
    type, id = el.split(" ")
    {:type => type, :id => id } 
}

Now you can address it like 'myarray[0][:type]'.

Rutger Nijlunsing
+9  A: 
string = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
string.scan(/(\w+)\s+(\d+)/).collect { |type, id| { :type => type, :id => id }}
molf
There's nothing wrong with Rutger's solution, but this feels a little more Ruby-ish to me. +1
James A. Rosen
A: 
   s = 'Purchases 10384839,Purchases 10293900,Purchases 20101024'
   myarray = s.split(',').map{|item| 
       item = item.split(' ')
       {:type => item[0], :id => item[1]} 
   }
toby
+1  A: 

Here is an irb session:

dru$ irb
irb(main):001:0> x = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
=> "Purchases 10384839,Purchases 10293900,Purchases 20101024"
irb(main):002:0> items = x.split ','
=> ["Purchases 10384839", "Purchases 10293900", "Purchases 20101024"]
irb(main):006:0> items.map { |item| parts = item.split ' '; { :type => parts[0], :id => parts[1] } }
=> [{:type=>"Purchases", :id=>"10384839"}, {:type=>"Purchases", :id=>"10293900"}, {:type=>"Purchases", :id=>"20101024"}]
irb(main):007:0>

Essentially, I would just split on the ',' first. Then I would split each item by space and create the hash object with the parts. No regex required.

drudru
+3  A: 

A regular expression wouldn't be necessary, and probably wouldn't be the clearest way to do it. The method you need in this case is split. Something like this would work

raw_string = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
myarray = raw_string.split(',').collect do |item|
  type, id = item.split(' ', 2)
  { :type => type, :id => id }
end

Documentation for the split and collect methods can be found here:

Enumerable.collect
String.split

Emily