Parsing a string in Ruby (Regexp?)

I have a line

Purchases 10384839,Purchases 10293900,Purchases 20101024

Can someone help me make out this? I tried using StringScanner, but I am not familiar with regular expressions (not a lot of practice).

If I could divide it into

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

That would be awesome!

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

You can do this with a regex or just do it in Ruby:

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

Now you can address it as "myarray [0] [: type]".

+11
source

, , . split. -

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

:

Enumerable.collect
String.split

+7

irb:

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 first split into ",". Then I would separate each element in space and create a hash object with parts. No regular expression required.

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

Source: https://habr.com/ru/post/1712041/


All Articles