Sam
Sam

Reputation: 1276

Parsing a String in Ruby (Regexp?)

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!

Upvotes: 3

Views: 7889

Answers (5)

Emily
Emily

Reputation: 18193

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

Upvotes: 7

drudru
drudru

Reputation: 5023

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.

Upvotes: 2

airportyh
airportyh

Reputation: 22668

   s = 'Purchases 10384839,Purchases 10293900,Purchases 20101024'
   myarray = s.split(',').map{|item| 
       item = item.split(' ')
       {:type => item[0], :id => item[1]} 
   }

Upvotes: 1

molf
molf

Reputation: 74935

string = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
string.scan(/(\w+)\s+(\d+)/).collect { |type, id| { :type => type, :id => id }}

Upvotes: 23

Rutger Nijlunsing
Rutger Nijlunsing

Reputation: 5001

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]'.

Upvotes: 11

Related Questions