0

现在我正在从另一个 url 获取数据......这是我的代码:

require 'rubygems'
    require 'nokogiri'

    html = page.body

    doc = Nokogiri::HTML(html)
    doc.encoding = 'utf-8'

    rows = doc.search('//table[@id = "MainContent_GridView1"]//tr')
      @details = rows.collect do |row|
          detail = {}
          [
            [:car, 'td[1]/text()'],
            [:article, 'td[2]/text()'],
            [:group, 'td[3]/text()'],
            [:price, 'td[4]/text()'],
          ].each do |name, xpath|
            detail[name] = row.at_xpath(xpath).to_s.strip
          end
          detail
      end
    @details  

我试图通过数组而不是哈希来做到这一点。但我得到了很多错误......有什么想法吗?我需要它用于另一种方法...

我还在这里将数据(此结果哈希)设置为另一辆车:

oem_art = []
    @constr_num.each do |o|
      as_oem = get_from_as_oem(o.ARL_SEARCH_NUMBER)
      if as_oem.present?
        oem_art << as_oem
      end
    end    

    @oem_art = oem_art.to_a.uniq
4

2 回答 2

1

Do you just want to change a hash into an array? If so, just use the to_a method on your hash.

hash = {:a => "something", :b => "something else"}
array = hash.to_a
array.inspect #=> [[:a, "something"], [:b, "something else"]]
于 2012-10-22T17:46:00.493 回答
0

看起来您正在寻找类似hash['key'] 到 Ruby 中的 hash.key 的东西

默认情况下, Hash 类不支持.key符号,OpenStruct 从 Hash 创建一个对象,因此您可以使用点符号来访问属性。总的来说,它基本上只是带有开销的语法糖。

建议的代码(来自链接的答案)

>> require 'ostruct'
=> []
>> foo = {'bar'=>'baz'}
=> {"bar"=>"baz"}
>> foo_obj = OpenStruct.new foo
=> #<OpenStruct bar="baz">
>> foo_obj.bar
=> "baz"

所以在你的例子中,你可以这样做:

# Initialised somewhere
require 'ostruct'
DETAIL_INDICES = { 
  :car => 1,
  :article => 2,
  :group => 3,
  :price => 4,
}

# ** SNIP **
@details = rows.map do |row|
  DETAIL_INDICES.inject({}) do |h,(k,v)| 
    h.merge(k => row.at_xpath("td[#{v}]/text()").to_s.strip) 
  end
end.collect { |hash| OpenStruct.new hash }

@details.each do |item|
  puts item.car
end

当然,如果性能是一个问题,你可以合并你的 map&collect (它们是相同的),但这只是基本语义差异的一个小分离,虽然我通常只map用于一致性,所以请随意选择自己:)

编辑——简化编辑中的附加代码

@oem_art = @constr_num.select do |item|
  as_oem = get_from_as_oem(item.ARL_SEARCH_NUMBER)
  as_oem.present?
end

puts @oem_art.uniq
于 2012-10-22T19:26:24.260 回答