【问题标题】:Grepping Ruby hash for regex not working as expectedGrepping Ruby hash for regex 没有按预期工作
【发布时间】:2018-05-22 22:23:34
【问题描述】:

我有这个数据的哈希:

{"ENABLED"=>
[#<Details:0x00007f910e946848
@context="ELP",
@instance="a1",
@side="blue",
@status="ENABLED",
@vm="ome-vm58",
@vmaddr="ajp://10.133.248.4:8009">,

... snip ...

#<Details:0x00007f910e944070
@context="learnItLive",
@instance="b2",
@side="green",
@status="ENABLED",
@vm="ome-vm61",
@vmaddr="ajp://10.133.248.7:8159">]}

哈希称为status_hash。我想确定密钥是否已启用。其他可能的键值是 DISABLED、STOPPED 和 WAITING。

这些行:

puts "Status key: " + status_hash.keys.to_s
puts "1 - Cluster has Disabled, Stopped, or Waiting contexts" if status_hash.keys.grep(/^[DSW]/)

产生输出,即使键是“ENABLED”

Status key: ["ENABLED"]
1 - Cluster has Disabled, Stopped, or Waiting contexts

我不明白为什么当键中的第一个字符是E 而不是DSW 时,正则表达式匹配。

【问题讨论】:

  • 你说,“我想确定 key 是否启用”(强调我的)。这向我表明哈希只有一个键。既然如此,你不想要简单的status_hash.keys.first == 'ENABLED'吗?
  • 我提供的示例只有一个键。有四个可能的键值,在错误情况下,会出现多个。

标签: ruby regex hash


【解决方案1】:

Enumerable#grep 总是返回一个数组,即使你的结果产生了[],这在 ruby​​ 中是真实的。

例子:

p 'hello world' if [].grep(/hi/).empty?
"hello world"
=> "hello world"
p 'hello world' if ![].grep(/hi/).empty?
=> nil

【讨论】:

    【解决方案2】:

    尝试在grep 结果上使用.any?

    puts "1 - Cluster has Disabled, Stopped, or Waiting contexts" if status_hash.keys.grep(/^[DSW]/).any?
    

    问题发生的原因是grep 返回了空数组[],这被认为是真实的。所以我们需要申请any?,如果数组中有任何元素则返回true。

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多