Reputation: 4649
I have a string something like this
JINSAL0056( 1), JINSAL0057( 1), JINSAL0041( 1),
I need to put JINSAL0056, JINSAL0057,JINSAL0041 in a field and number inside the (). I have written couple of codes let me know if I am going in the right directions.
s = "JINSAL0056( 1), JINSAL0057( 1), JINSAL0041( 1)"
ss = s.split(",")
sss = ss.split(" ( ")
How to write the split. Please do help me put
Upvotes: 0
Views: 215
Reputation: 80065
s = "JINSAL0056( 1), JINSAL0057( 1), JINSAL0041( 1)"
res = s.split(', ').map{|line| line.chop.split('( ')}
p res # [["JINSAL0056", "1"], ["JINSAL0057", "1"], ["JINSAL0041", "1"]]
res.each do |jinsal, number|
puts "Do something with #{jinsal} and #{number}"
end
Upvotes: 2
Reputation: 24256
I think you can try. (Not the best way of course.)
yourstring = "JINSAL0056( 1), JINSAL0057( 1), JINSAL0041( 1),"
yourstring.split(/(\w+)\(\s*(\d)\)[,\s*]/)
Result will be
["", "JINSAL0056", "1", " ", "JINSAL0057", "1", " ", "JINSAL0041", "1"]
but I recommended to use scan(//)
yourstring.scan(/(\w+)\(\s*(\d)\)[,\s*]/)
Result will be
[["JINSAL0056", "1"], ["JINSAL0057", "1"], ["JINSAL0041", "1"]]
to assign variable you can loop like this
yourstring.scan(/(\w+)\(\s*(\d)\)[,\s*]/).each do |a,b|
puts "#{a} #{b}"
end
Upvotes: 4
Reputation: 16274
You can pass regexes to split too:
foo = "JINSAL0056( 1), JINSAL0057( 1), JINSAL0041( 1),"
foo.split(/[\(\),\s]+/)
The result:
["JINSAL0056", "1", "JINSAL0057", "1", "JINSAL0041", "1"]
And make it into a hash:
Hash[*foo.split(/[\(\),\s]+/)]
Which will give you:
{"JINSAL0056"=>"1", "JINSAL0057"=>"1", "JINSAL0041"=>"1"}
Upvotes: 5