IF语句不使用nokogiri在这种方法中工作

时间:2014-07-09 14:07:50

标签: ruby-on-rails ruby nokogiri

这是我的简单代码。我发现这个 IF语句的问题是为数组中的每个项目寻找一个元素。

现在我的问题是代码卡在IF语句的第一部分。我在 train_tables 中的两个项目只有一个 TrainPathNotAvailable 。我希望如果其中一个项目没有 TrainPathNotAvailable ,它应打印出'秒IN' 但它不会 正确?

谢谢你的时间! 代码的网址:here

 def self.opening_file
    @train_at_path_locations
    doc = Nokogiri::XML(File.open("test_with_path.xml"))
    @train_tables = doc.css("TrainTimeTable")

    puts @train_tables.count # I have just 2 items to make this test easy

    @train_tables.each do |i|

      @train_id = i.css('TrainIdent PathIdent')
      @train_locations = i.css('TrainAtPathLocation')

      if i.css('TrainPathNotAvailable')  #here is the problem
        puts 'first IN'
        # @first_station_not_available = i.css('FromLocationIdent LocationSubsidiaryCode')
        # puts @train_location_last = i.css('ToLocationIdent LocationSubsidiaryCode').text
        break
      else
        puts 'second IN'
        # @train_location_first = i.css('TrainAtPathLocation LocationIdent LocationSubsidiaryCode').first
        #
        # puts @train_location_last = i.css('TrainAtPathLocation LocationIdent LocationSubsidiaryCode').last
      end

    end

1 个答案:

答案 0 :(得分:0)

尝试at_css而不是css。

css将返回一个空数组[],当它找不到任何内容时,这是一个真正的值,导致你的if语句被触发。

如果找不到任何内容,

at_css将返回nil。

如果需要返回一个数组,请尝试使用css()。any?