【问题标题】:Is it possible to dynamically set variables in ruby?是否可以在 ruby​​ 中动态设置变量?
【发布时间】:2014-12-18 09:11:21
【问题描述】:

我想知道如果这些全局变量存在并且可以被其他函数访问,我想知道是否有可能告诉函数使用一个或另一个变量而无需重新编写大量代码。我必须使用全局变量,因为我对葫芦传递变量的限制(如果我错了,请纠正我)。我希望能够调用一个可以获取信息并将其填充到多个全局变量之一的函数。希望是这样的:

def add_five(my_var)

   if my_var == "my_cats"
      use $my_cats for my_var_nickname
   elsif my_var == "my_dogs"
      use $my_dogs for my_var_nickname
   elsif my_var == "my_birds"
      use $my_birds for my_var_nickname
   end

   my_var_nickname = my_var_nickname + 5
end

$my_cats = 2
$my_dogs = 3
$my_birds = 3

add_five("my_cats")

$my_cats = 7
$my_dogs = 3
$my_birds = 3

感谢您的帮助!

【问题讨论】:

  • 你可以写b = ((stuffy == "foo") ? $A : $B),然后使用b,但是你应该尽量避免使用全局变量。
  • 像这样使用全局变量 ($) 会产生明显的代码异味。
  • 不幸的是,我在使用葫芦时没有太多选择。我需要一种在测试步骤之间来回记录和交流数据的方法。

标签: ruby variables dynamic global-variables calabash


【解决方案1】:
def record_as(stuff)
   variable_to_use = if stuff == "foo"
      $variableA
   elsif stuff == "bar"
      $variableB
   end

   #do stuff with variable_to_use
end

【讨论】:

  • 将其保存在原始变量中还是只是复制它以在该函数中使用?
  • 这会创建一个对变量的新引用,因此编辑新引用将反映在全局
  • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • 我试过了,但信息从未返回到全局变量中。不过,这可能与它也处于葫芦步骤的中间这一事实有关。
  • 我们不使用variableA 作为Ruby 中的变量名,无论它们是否是全局的。相反,使用snake_case,variable_a
【解决方案2】:

我认为使用全局变量有异味...

无论如何,您可以尝试使用hash

$animal_counts = {}
def add_five(animal_type)
  $animal_counts[animal_type] += 5
end

$animal_counts[:cats]  = 2
$animal_counts[:dogs]  = 3
$animal_counts[:birds] = 3

add_five(:cats)

$animal_counts[:cats]  # => 7
$animal_counts[:dogs]  # => 3
$animal_counts[:birds] # => 3

希望有帮助!

【讨论】:

  • 嗯,这很有趣。在我的实际情况下,全局变量本身已经是哈希值......我将不得不再研究一下。
【解决方案3】:

为了简单的使用 在你的 ruby​​ 步骤文件中定义一个像这样的变量

$global_memory=""

在您的葫芦步骤中,可以在另一个 ruby​​ 步骤文件中。 从查询中读取一些文本并在运行时将其存储在该变量中。

Then I should memorize delivery time

像这样在 ruby​​ 步骤文件中定义

Then /^I should memorize delivery time$/ do
  srctext=query("label marked:'lblOrderTime'",:text).first
  srctext=srctext.to_s
  $global_memory.replace(srctext)
end

稍后在场景中,您可以调用该值并像这样使用它

Then I should see order dispatch time same as in checkout screen and receipt screen

像这样在 ruby​​ 步骤文件中定义

Then /^I should see order dispatch time same as in checkout screen and receipt screen$/ do |arg|
  datetext=$global_memory
    result = query("webView css:'SPAN' index:5").first["textContent"].include? "#{datetext}"
    unless result
      textFound = query("webView css:'TABLE' index:0").first["textContent"]
      screenshot_and_raise "time  #{datetext} not found instead #{textFound} is found"
    end 
end

您还可以使用哈希(键值对)同时存储多个变量并检索它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2017-03-10
    • 1970-01-01
    相关资源
    最近更新 更多