Hi
I have working code that I have currently loops through an example returning matches via nokogiri module.
This works
require 'nokogiri'
require 'awesome_print'
@doc = Nokogiri::XML(File.open('/home/sayth/data/20160702RHIL0.xml'))
@doc.search('race').map do |race|
nominations = race.search('nomination')
.map do |nomination|
{
number: nomination['number'].to_i,
id: nomination['id'].to_i,
horse: nomination['horse'].to_s,
age: nomination['age'].to_i,
sex: nomination['sex'].to_s,
colour: /\W(.+?)\d?\s/.match(nomination['description'].to_s)[1]
}
end
a = { race['id'].to_i => nominations }
ap a
end
_______________________________________________________________________________
So at this point I know that I need to replicate this for 6 sections in total, logically to me then I want to abstract especially the middle.
{
number: nomination['number'].to_i,
id: nomination['id'].to_i,
horse: nomination['horse'].to_s,
age: nomination['age'].to_i,
sex: nomination['sex'].to_s,
colour: /\W(.+?)\d?\s/.match(nomination['description'].to_s)[1]
}
and substitute a variable into race.search('nomination') this to replace the word nomination and to then replace all 'nomination' in the above section.
So this is what I have done.
data = %w(number id horse age sex colour)
def extract_value(path_id, data)
@doc.search('race').map do |race|
puts path_id
nominations = race.search(path_id)
.map do | |
data
end
values = { race['id'].to_i => nominations }
ap values
return values
end
end
extract_value('nomination', data)
_______________________________________________________________________________
The main part I cannot wrap my head around is how to get these sections in without replicating it in the definition.
number: nomination['number'].to_i,
How can I better abstract this out?
This is close.
However not all values are integers, some are strings.
Can you make templates that you can drop into the function?
PS I learnt tap from your previous post I had thought it was a typo of map but no http://ruby-doc.org/core-2.3.1/Object.html#method-i-tap :-)
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 293 |
Nodes: | 16 (2 / 14) |
Uptime: | 242:57:44 |
Calls: | 6,625 |
Calls today: | 1 |
Files: | 12,175 |
Messages: | 5,320,203 |