2013-05-14 79 views
0

我想读取一个XML文件并将结构存储到一个对象数组中。这里是我的代码:如何从循环内部返回值?

class Bike 
    attr_accessor :id, :color, :name 
    def initialize(id, color, name) 
     @id = id 
     @color = color 
     @name = name 
    end 
end 

---x---snip---x--- 

rules.root.each_element do |node1| 
    case node1.name 
    when "Bike" 
     bike = Bike.new(node1.attributes['id'], node1.attributes['color'], { |bike_elem| bike_elem.text.chomp if bike_elem.name == "name"}) 
     bikes.push bike 
    end 
end 

但是,最后一个元素没有单独获取值。它正在读取整个标签。有没有更好的方法来做到这一点?

+0

我不认为这是一个有效的Ruby表达式。 – sawa 2013-05-14 16:50:42

+0

我不认为你的问题与迭代(或者说,你的话中的“循环”)有任何关系。 – sawa 2013-05-14 16:53:00

回答

1

您的代码块{ |bike_elem| bike_elem.text.chomp if bike_elem.name == "name" }new参数列表中似乎没有意义。

bike_elem从哪里来?在这种情况下,这不是有效的Ruby。

如果不知道XML是什么样子,很难在这里给出答案。 但我建议使用像Nokogiri这样的XML库,libxml,然后在执行new之前解析出名称 。尝试使用XPath

rules.root.each_element do |node1| 
    case node1.name 
    when "Bike" 
     name = node1.attributes[....] 
     bike = Bike.new(node1.attributes['id'], node1.attributes['color'],name) 
     bikes.push bike 
    end 
end 
+0

是不是bike_elem.text.chomp最后一个被评估? – 2013-05-14 16:51:14