从KRL中的散列中检测空的pick()

时间:2011-01-03 22:30:42

标签: hash krl

我在哈希中有一堆数据,我正在从中挑选。有时会有数据可供选择,有时则不会。有什么最好的方法可以知道pick操作符何时找到了什么,什么时候没有,我可以在代码中对此做出反应?

1 个答案:

答案 0 :(得分:4)

pick operator将采用第二个可选参数,使其始终返回数组中的结果。这意味着如果选择某些内容,则数组的长度将大于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;
    }
  }
}