Lifeweaver
Lifeweaver

Reputation: 1042

Not finding hash key values with regex

I have a hash that will have entries similar to entry1, entry2, etc and I'm trying to count how many times they appear but I also have an entry similar to entry_hello. So when I try to count how many times they appear the 'entry_hello' is also counted. I have this code here to see if each entry matches or not but this doesn't work as I expected.

hash = {}
hash['entry'] = 'Test1'
hash['entry_date'] = 'Test2'
hash['entry2'] = 'Test3'

hash.each do |x|
puts x.to_s.scan(/entry\d?$/).count
end

But in this case nothing is found, but without the $ the 'entry_hello' is counted. I've tried with strings and this works but when I try it with hash keys it doesn't. I don't understand why it doesn't work, and would like to know ether how to get this to work or another method to do this.

UPDATE: For anyone who cares: The reason my code didn't work is because x in this case was the key/value pair so x didn't equal 'entry' or 'entry2' but instead equaled 'entryTest1' or 'entry2Test3'.

Sawa's answer works since the the underscore in hash.count{|k, _| k =~ /\Aentry\d?\z/} is meant to indicate that while the closure takes a second argument, it will not be assigned a value.

I'm probably going to go ahead and use hash.keys.count{|k| k =~ /\Aentry\d?\z/ } since this is more understandable to me. The key here is the key's part as now you are only looking at the keys of the hash not both keys and values.

Upvotes: 2

Views: 545

Answers (1)

sawa
sawa

Reputation: 168121

hash.count{|k, _| k =~ /\Aentry\d?\z/}

'entry_date' will match /entry\d?/ without \z or $.

Upvotes: 2

Related Questions