1

我正在使用 find_index 来查找一个元素,然后单击它的链接。但是,当索引返回 nil 时,它会单击元素 0 的链接。是否有正确的方法来失败?

这是我的代码:

def index_for(fruit)
   index = fruits_elements.find_index{|f| f.div_element.text == fruit}
   index
end
def click_on_product(fruit)
  index = index_for(fruit)
  fruits_element[index.to_i].link_element.click
end

理想情况下,如果找不到,我希望它失败。目前它在返回 nil 时单击元素 0。一如既往地感谢您的帮助。

4

1 回答 1

2

只需进行如下更改

def click_on_product(fruit)
  index = index_for(fruit)
  begin
  # will throw type error, when index is nil.
  fruits_element[index].link_element.click
  rescue TypeError => ex
    # any exception related message if you want to print
    # should be here.
  end
end

但是,当索引返回 nil 时,它会单击元素 0 的链接。是否有正确的方法来失败?

看,你index.to_i在行中使用了 , fruits_element[index.to_i].link_element.click。现在,NilClass#to_i方法,实际上返回0. 因为nil.to_i0。因此fruits_element[index.to_i]实际上变成fruits_element[0]了,这是第一个元素,正如您所报告的那样获得点击。

当你想引发错误时,不要to_i在那里使用方法。

find_index方法要么在找到时返回整数,要么nil在未找到时返回。我认为根据您的代码,没有必要将整数再次转换为整数,因为您有兴趣抛出错误。

您还应该编写如下方法index_for

def index_for(fruit)
   fruits_elements.find_index {|f| f.div_element.text == fruit }
end

您不需要将变量写index为最后一个表达式来返回它。因为在 Ruby 中,默认返回方法的最后一个表达式。

于 2014-03-17T01:52:26.583 回答