Mark Nichols
Mark Nichols

Reputation: 1503

Grepping Ruby hash for regex not working as expected

I have a hash with this data:

{"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">]}

The hash is called status_hash. I want to determine if the key is ENABLED or not. The other potential key values are DISABLED, STOPPED, and WAITING.

These lines:

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

Produces output, even though the key is "ENABLED"

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

I don't understand why the regex is matching when the first character in the key is an E and not in DSW.

Upvotes: 1

Views: 83

Answers (2)

Abdullah
Abdullah

Reputation: 2111

try using .any? on grep results

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

The reason, why the issue was occurring, was grep returned empty array [] which is considered truthy. So we need to apply any?, which returns true if there is any element in an array.

Upvotes: 1

Anthony
Anthony

Reputation: 15967

Enumerable#grep always returns an array and even though your results produces [] that is truthy in ruby.

Example:

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

Upvotes: 2

Related Questions