0

这主要是一个 Ruby 问题,但我已将其标记为 watir-webdriver,因为该示例包含 watir-webdriver 代码,希望它能提高清晰度。

我有一个类可以检索和更新在网页上找到的数据。该数据存储在类的实例变量中。

该类包含一个方法,该方法将使用现有的实例变量值来更新网页上的选择列表,或者,如果实例变量为 nil,它将获取选择列表的值并将其存储在实例变量中。

该方法当前如下所示:

def get_or_select!(inst_var_sym, select_list)
  value = instance_variable_get inst_var_sym
  if value==nil
    instance_variable_set inst_var_sym, select_list.selected_options[0].text
  else
    select_list.select value
  end
end

这行得通,但我想知道是否有一种方法可以编写方法,使其可以直接应用于实例变量(而不是实例变量的符号匹配器),并将 select_list 对象作为其单个参数。

换句话说,目前看起来像这样:

get_or_select!(:@instance_variable, select_list)

我想看起来像这样:

@instance_variable.get_or_select!(select_list)

这甚至可能吗?

4

1 回答 1

1

新答案:由于变量在您定义它之前不存在,因此您不能在其上调用方法。调用类必须设置它。你可以做一个简单的 if 检查。

#In the calling class, not the variable class  
  if @instance_variable       # If it is defined, this is true
    returned_list = select_list.select @instance_variable.value # Gets the selected list 
  else
    @instance_variable = instance_variable_set inst_var_sym, select_list.selected_options[0].text
  end

下面的旧答案:你不能使用条件赋值吗? http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators#1._Assignment

x = find_something() #=>nil
x ||= "default"      #=>"default" : value of x will be replaced with "default", but only if x is nil or false
x ||= "other"        #=>"default" : value of x is not replaced if it already is other than nil or false

所以对于这个它会是这样的......

instance_variable_get inst_var_sym ||= instance_variable_set inst_var_sym, select_list.selected_options[0].text
于 2013-01-29T21:45:22.990 回答