4

我在哈希中有一堆数据,我正在从中挑选。有时会有数据可供选择,有时则不会。什么是知道挑选操作员何时找到某些东西以及何时没有找到的最佳方法,以便我可以在我的代码中对此做出反应?

4

1 回答 1

4

选择运算符将采用第二个可选参数,使其始终以数组的形式返回结果。这意味着如果选择了某些东西,则数组的长度将大于 0,否则将为 0。然后您可以使用它来做您想做的事情。

示例代码/应用取自http://kynetxappaday.wordpress.com/2011/01/04/day-30-detecting-empty-pick/

ruleset a60x526 {
  meta {
    name "hash-pick-detect"
    description <<
      hash-pick-detect
    >>
    author "Mike Grace"
    logging on
  }

  global {
    dataHash = {
      "one": {
        "name": "Mike"
      }, // number
      "two": {
        "random": 8
      }, // number
      "three": {
        "name": "Alex"
      } // number

    }; // dataHash

  } // global

  rule detect_the_pick {
    select when pageview ".*"
    foreach dataHash setting (key, value)
    pre {
      userName = value.pick("$.name", true);
      length = userName.length();
    }
    if (length > 0) then {
      notify("Key: #{key}","Name: #{userName}<br/>Length: #{length}") with sticky = true;
    }
    notfired {
      raise explicit event empty_pick
        with pickedKey = key;
    }
  }

  rule empty_pick_found {
    select when explicit empty_pick
    pre {
      pickedKey = event:param("pickedKey");
      results =<<
        Key: #{pickedKey}<br/>
        doesn't have a name associated with it to pick from
      >>; //' fixing syntax highlighting
    }
    {
      notify("An empty pick was detected",results) with sticky = true;
    }
  }
}
于 2011-01-03T23:21:58.200 回答