or even better can I do hash.has_key?('videox')
where x is
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...
In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .
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$") }
One possibility:
hash.values_at(:a, :b, :c, :x).compact.length > 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With