产生阵列

时间:2012-11-01 14:51:04

标签: ruby

不确定我的问题是否正确,但一般情况下我会执行以下操作:

给出如下代码片段:

[{ <some events>, "close"}, { <some other events>, "close"}].each do |events|
    it "should handle events" do
        ...
    end
    ...
end

我想增加事件的数组。假设关闭有两种方式:"close"(相同)和"stop"。这意味着,我想编写一些代码来检查4个序列:[{<some events>, "close"}, {<some other events>, "close"}, {<some events>, "stop"}, {<some other events>, "stop"}]

什么是正确的(Ruby样式)编码方式?

更新<some events><some other events>是字符串序列(这只是为了澄清)。

更新N2: stopclose更常见的情况也可以出现在序列的中间。

更新N3:只是可能do处拥有单个最终序列会更方便。我可能在这里错了。

更新N4:示例(只是为了清楚地说明):

  

初始消息:“open”,“click_btn1”,“click_btn2”,   “open”,“click_btn2”,“click_btn3”,

     

期望的结果:“打开”,“click_btn1”,“click_btn2”,“关闭”“打开”,   “click_btn1”,“click_btn2”,“关闭”,“打开”,“click_btn2”,   “click_btn3”,“停止”,“打开”,“click_btn2”,“click_btn3”,“停止”

1 个答案:

答案 0 :(得分:2)

只需嵌套迭代。

[some_events, some_other_events].each do |event|
  ["close", "stop"].each do |close_or_stop|
    ...
  end
end

或者

[some_events, some_other_events].product(
["close", "stop"]) do |event, close_or_stop|
  ...
end