tags:

views:

171

answers:

2

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

  • '' nothing or
  • a digit?

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

of course I can have two conditions but in case I need to use video3 in the future things would get more complicated...

+5  A: 

One possibility:

hash.values_at(:a, :b, :c, :x).compact.length > 1
DigitalRoss
@DigitalRoss: where :a,:b ect would be video, video1 etc?
Radek
Right, and at some point (1.9?) Array got an `abbrev` method which really does exactly what you want. I think that would go something like `hash.keys.abbrev 'video'`
DigitalRoss
+5  A: 

If you want the general case of video followed by a digit without explicitly listing all the combinations there are a couple of methods from Enumerable that you could use in combination with a regular expression.

hash.keys is an array of the keys from hash and ^video\d$ matches 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 would also allow you to capture the matching key(s) if you needed that information for the next bit of your code e.g.

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

Furthermore, if the prefix of key we're looking for is in a variable rather than a hard coded string we can do something along the lines of:

prefix = 'video'
# use an interpolated string, note the need to escape the
# \ in \d
hash.keys.any? { |k| k.match("^#{prefix}\\d$") }
mikej
severin
@mikej: I like the way you explain everything... could you please also add to your answer how the code would look like if we use variable name instead of the actual string 'video'?. Thank you
Radek
@Radek updated the answer to show a case of where the prefix is in a variable. Hope this is the kind of thing you had in mind.
mikej
@mikej: I figured the syntax for variable but with bit of troubles. I thought the answer could be perfect for other .... Thank you for great job!
Radek