Can I do hash.has_key? ('video' or 'video2') (ruby)

or even better, can I do hash.has_key?('videox') , where x is

  • '' nothing or
  • numeral?

so will 'video', 'video1', 'video2' pass the condition?

Of course, I can have two conditions, but in case I need to use video3, in the future everything will become more complicated ...

+7
ruby hash
source share
2 answers

If you want the general case of a video to be accompanied by a number without explicitly listing all the combinations, there are several methods from Enumerable that you can use in combination with a regular expression.

hash.keys is an array of keys from hash and ^video\d$ corresponds to a video followed by a digit.

 # true if the block returns true for any element hash.keys.any? { |k| k.match(/^video\d$/ } 

or

 # grep returns an array of the matching elements hash.keys.grep(/^video\d$/).size > 0 

grep will also allow you to capture the appropriate key (s) if you need this information for the next bit of your code, for example.

 if (matched_keys = hash.keys.grep(/^video\d$/)).size > 0 puts "Matching keys #{matched_keys.inspect}" 

In addition, if the key prefix we are looking for is in a variable, and not in a hard-coded string, we can do something in the following lines:

 prefix = 'video' # use an interpolated string, note the need to escape the # \ in \d hash.keys.any? { |k| k.match("^#{prefix}\\d$") } 
+12
source share

One possibility:

 hash.values_at(:a, :b, :c, :x).compact.length > 1 
+6
source share

All Articles