Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

hash

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...

like image 699
Radek Avatar asked Feb 18 '10 06:02

Radek


People also ask

How do I get the hash value in Ruby?

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.

How do you write a hash in Ruby?

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.

How do you know if something is a hash?

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 .


2 Answers

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$") }
like image 115
mikej Avatar answered Oct 09 '22 22:10

mikej


One possibility:

hash.values_at(:a, :b, :c, :x).compact.length > 1
like image 35
DigitalRoss Avatar answered Oct 09 '22 22:10

DigitalRoss