3

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!

5 Answers 5

23
string = "Purchases 10384839,Purchases 10293900,Purchases 20101024"
string.scan(/(\w+)\s+(\d+)/).collect { |type, id| { :type => type, :id => id }}
Sign up to request clarification or add additional context in comments.

2 Comments

There's nothing wrong with Rutger's solution, but this feels a little more Ruby-ish to me. +1
This answer has saved me <3
11

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

Comments

7

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

Comments

2

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.

1 Comment

No regexp required, but maybe regexp recommended? I wonder which one would be more efficient.
1
   s = 'Purchases 10384839,Purchases 10293900,Purchases 20101024'
   myarray = s.split(',').map{|item| 
       item = item.split(' ')
       {:type => item[0], :id => item[1]} 
   }

1 Comment

Just a quick question: what's the difference between map and collect?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.