【问题标题】:Change Ruby Hash Value from Given Cucumber Table从给定的 Cucumber 表中更改 Ruby 哈希值
【发布时间】:2014-06-27 08:33:28
【问题描述】:

我正在将一个表从 cucumber 传递到 Ruby,尝试更改哈希值,然后我想将该表传递到下一步。哈希值发生变化,但表不受影响。我做错了什么,或者在这里遗漏了一些概念。请指教!

我的黄瓜示例:

Scenario:  Change Table Value
  Given I start with this table
  | person | grade |
  | Bob    | 82    |
  | Jim    | 94    |
  | Bill   | 58    |

这是红宝石:

Given /^I start with this table$/ do |table|
  puts "table is:"
  puts table
  table.hashes.each do |hash|
    puts "hash is:"
    puts hash

    puts "hash['person'] = #{hash['person']}"
    puts "assigning new name..."
    hash['person'] = 'Superman'
    puts "hash['person'] = #{hash['person']}"

    puts "hash is:"
    puts hash
  end
  puts "table is:"
  puts table
end

输出显示哈希值确实发生了变化,但表的最终puts显示原表没有受到影响。

我想将该表作为新值的输入传递到下一步。

任何建议将不胜感激, 谢谢, 埃德

【问题讨论】:

    标签: ruby hash cucumber


    【解决方案1】:

    您可以将转换后的表设置为实例变量以供下一步读取:

    Given /^I start with this table$/ do |table|
      @hashes = []
      table.hashes.each do |hash|
        hash['person'] = 'Superman'
        @hashes << hash
      end
    end
    
    Then /^I can read the transformed data$/ do
      @hashes.each do |hash|
        puts hash
      end
    end
    

    【讨论】:

    • 谢谢你,乌里。为了避免使用实例变量,我是否可以将哈希直接传递给另一个需要表作为输入的步骤(与第一步非常相似?)(原因是我已经有一个需要使用的表的步骤其他已经存在的小黄瓜。我本质上是想预处理哈希并将其传递给预先存在的步骤。)
    • @Ed_ - 我不知道,但您可以使用保护条件来支持是否有预处理步骤 ((table.try(:hashes) || @hashes).each do |hash|...)
    • 好的。谢谢你的回答,乌里。我还不允许“投票”你的回复,否则我会的。再次感谢。 - 埃德
    • @Ed_ - 如果它解决了你的问题 - 你可以接受它。
    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    • 2015-09-15
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多