Regarding the following code:
update:
(thank you DGM and The Tin Man for recomendation on code and apneadiving for explanation.)
#################
# get main page
#################
rows = doc.xpath('//table[@class="articulos"]/tr[td[5]/p/b]')
i = 0
details = rows.each do |row|
detail = {}
[
[:sku, 'td[3]/text()'],
[:desc, 'td[4]/text()'],
[:stock, "td[5]/p[@title]"],
[:price, 'td[6]/text()']
].each do |name, xpath|
detail[name] = row.at_xpath(xpath).to_s.strip
end
i = i + 1
if detail[:sku] != ""
price = detail[:price].split
if price[1] == "D"
currency = 144
else
currency = 168
end
stock = detail[:stock].gsub(/[^\d]/, '')
cost = price[0].gsub(",", "").to_f
end
- Is the first
i = 0,i = i + 1neccesary? - What syntax is this using?
details = rows.each do |row| - Why would you want to use
detail = {}? What is this doing? - I do understand
.each do |name,xpath|because it is in the order:name,xpath. - I guess
detail[name] = row.at_xpath(xpath).to_s.stripis saying that, if I calldetail[:sku], it will make that row at thatxpathto a string strip.
for what I understand after reading Ruby Poignant Book reading the code I wrote above I can maybe translate to Ruby logic words?. If that is not to insulting for Ruby Experts,haha.
First we have a loop of one method, with an array of arrays, inside another one.
variable = variable.method block |block argument|
variable = {block}
[ array of arrays
[ symbol_1, 'string'],
[ symbol_2, 'string'],
[ symbol_3, 'string'],
[ symbol_4, 'string'],
[ symbol_5, 'string'],
[ symbol_6, 'string']
].method block |symbol, string|
variable[symbol] = variable.method(method argument).method.kernel_method
end block
end block
??? is this correct? now I need to explain that using the method , variable, and arguments actual names in the code, lets see:
The rows variable gets a collect message to collect a row of an array of arrays containing the symbol and xpath and for each block of arrays the row and xpath wil be applied a kernel method strip?
it’s useless, you’re right
it’s sheer ruby style, it loops the elements of what should be an Array.
It also recreates an Array stored in
detailscontaining every element declared at the end of the loop. Here it’sdetailIt initializes
detailto an empty Hash which is then filled in thecollectloop.Correct.
maploops all the elements of what should be a Hash. It creates an Array containing links. Duplicates of links are removed from this Array thanks touniq!Notice the bang at then end of this function, it means it changes the object.
Don’t understand this question.
It’s a push but it’s
details << detailso logic is safe.To conclude, it’s not beautiful code but it seems functional 🙂