I actually doing some play with nokogiri methods since last 3 days.
Doing so I have ended up with the below code:
require ‘nokogiri’
doc = Nokogiri::XML(<<-eohl)
7052
PADINI
1.2
1.1
10.0
3000000L
1.3
1.2
11.0
5000000L
eohl
doc.at_css(“StockDailyRecords”).children.map{|el| el.text.strip if
el.text.strip != “” }.compact
=> [“1.2”, “1.1”, “10.0”, “3000000L”]
but my code not seems to be a Rubyistic. Any good approach would anybody
give me? :)))
Basically I want to shorten my code oc.at_css("StockDailyRecords").children.map{|el| el.text.strip if el.text.strip != "" }.compact. its too ugly I think.
doc.at_css(“StockDailyRecords”).children.map{|el| el.text.strip if
el.text.strip != “” }.compact
=> [“1.2”, “1.1”, “10.0”, “3000000L”]
but my code not seems to be a Rubyistic. Any good approach would anybody
give me? :)))
I actually do not have a clue what you mean by that? Did you not get
what you expected? If you did get what you expected, I don’t see
anything wrong with your code… There are other ways to do that, of
course, but they’re not more idiomatic, if that’s what you mean, and can
be much worse.
This could work as well:
doc.at_css(“StockDailyRecords”).children.map(&:text).map(&:strip).select{|el|
not el.empty?}
but it’s not better; It’s actually worse, IMO, because it’s rolling
through the collection several times.
Yet another:
doc.at_css(“StockDailyRecords”).children.select do |el|
el.text.strip!; el unless el.empty?
end
which has the side effect of changing the contents of doc, in my opinion
is dangerous.
And there’s inject/reduce, which can be even more arcance/opaque:
doc.at_css(“StockDailyRecords”).children.reduce([]) do |m,o|
o = o.text.strip
m << o unless o.empty?
m
end
Given time, I could probably come up with a few more. But that’s
moot. Your code is fine.