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

-------------Problems Reply------------

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

Category:ruby Views:0 Time:2010-02-18
Tags: ruby hash

Related post

  • Any way to get the title or name of a hash and/or array in ruby 2011-08-10

    So pretty straight forward but I cant find the answer. Say i have an object dumped in YAML as such: page: page_url: http://www.stackoverflow.com/ created_at: "2011-08-10T11:00:19Z" website_id: 1 updated_at: "2011-08-10T11:00:19Z" id: 1 Hash I know fr

  • How to find out if a key exists in a hash, then use that information ruby 2011-10-04

    I have read the lines of a text file into a hash of chars. Now I need to make it so only the alphabetical chars appear, not the special chars and punctuation. I have tried this: File.open(WORKING_DIR + '/code.txt','r') do |f| char_count = Hash.new(0)

  • Need to know how hash key are handled in ruby 2009-11-11

    I am working on ruby rails project. I am using Rails 2.3.4 and ruby 1.8.7 . I have a model called User. I have following code in initializer $h = {User => 'I am user' } In the controller I have following code $h[User] First time when I do h[User]

  • How can i render a json response from a hash while maintaining order in ruby on rails? 2010-02-10

    hey out there, i am failing to render a json response in ruby on rails from a hash datastructure of country-names with their country-codes: { "AF"=>"Afghanistan", "AL"=>"Albania", "DZ"=>"Algeria", ... }, so that the json response has its ent

  • How out of date is the "blog tutorial" video on the ruby on rails website? 2010-03-01

    Hay, with the release of Ruby on Rails 3 soon, I thought I'd dive back into a bit of Ruby on Rails programming. I missed out version 2 of rails and had only previously been using 1.2 So i hopped on the video tutorial and worked through it. I just wan

  • Return hash with modified values in Ruby 2010-04-03

    I'm trying this: {:id => 5, :foos => [1,2,3]}.each {|k,v| v.to_s} But that's returning this: {:id=>5, :foos=>[1, 2, 3]} I'd like to see this: {:id=>"5", :foos=>"[1, 2, 3]"} I've also tried variations of Hash#collect and Hash#map. An

  • Complex hash editing with MVC/Padrino ruby 1.8.x 2010-06-24

    I'm new to MVC. I'm using Padrino with MongoMapper and Haml to try to create this application. I have a database of items, each of which has a hash associated with it called 'params'. This hash has some required keys, but mostly arbitrary/random keys

  • access to hash through an variable in ruby on rails 2010-08-16

    Hello I have following problem. I have a hash filled with the html parameters (params): Parameters: "info"=>{"parameter2"=>{"r1"=>"aa", "r2"=>"bb", "r3"=>"cc", "r4"=>"dd", "r5"=>"ee"} You can access this values like this: <%=

  • How to split a hash based on values in Ruby? 2010-08-31

    I have a hash in Ruby that is storing the word frequency of a string, with the word as the key and the frequency as the value. words = a_string.split(/ /) freqs = Hash.new(0) words.each { |word| freqs[word] += 1 } freqs = freqs.sort_by {|x,y| y } fre

  • Updating nested hash parameters. Update action, ruby on rails 2010-11-01

    I have a nested form that includes a lesson/questions/answers. The user populates answer fields and clicks submit. The hash is shown below: Parameters: {"commit"=>"Submit Answers", "action"=>"update", "_method"=>"put", "authenticity_token"=

  • Embedded Youtube video in a Ruby on Rails page 2010-12-25

    New to programming. I am trying to embed a YouTube video from a link stored in a database named "Promoter" into a ruby-on-rails page (.erb). I've looked at the source the code turns out, but the object video player does not appear (on heroku here: ht

  • Trying to play an mp4 video on a ruby mongrel server 2011-04-09

    Hello I am trying to run a ruby mongrel server on windows 7. I am using some video-js code to display a video. <title>Waza Player</title> <script src="video.js" type="text/javascript" charset="utf-8"></script> <script type=

  • Easy way to access hashes from within arrays with ruby 2011-06-12

    I'm using ruby to get get some address information from the Google geocode API. I get JSON returned and parse this into a variable which is an array containing hashes. After I've parsed the json it looks like this {"status"=>"OK", "results"=> [

  • Extract the hash from Torrent File in ruby 2011-06-27

    I was hoping to extract the hash identifier for a torrent file. Particularly, I'm looking for the same hash that shows up in Transmission/uTorrent upon opening up a torrent info dialogue (It looks like this: 7b435a6f051dec092a6ee440d793bfed6696cfa1)

  • embedding a youtube video using haml/ruby on rails 2011-07-19

    I have a website with a textarea that prompts users to input a URL from a youtube video. Once the user saves the page (thereby saving the embed code) I would like to implement an iframe on the page so that users can see the video they embedded. at pr

  • new-style hash argument available error in Ruby 1.9.3 2011-11-05

    I just moved a project to another server and seem to be having problems related to the new new hash argument available since Ruby 1.9.2. When I run rails s I get the following error Exiting /usr/lib/ruby/gems/1.8/gems/activesupport-3.1.1/lib/active_s

  • issue in passign hash values across objects in ruby onr rails 2012-01-07

    I am running into problems passing a hash (serialized as a hash) to a newly created object. The values get converted to yaml format. Consider the following: Model ComputerUser: ... serialize preferences '#in the database I see the following "{0=>{

  • Getting video metadata in ruby script using ffmpeg, ffprobe or rvideo 2012-01-19

    I want to get metadata of videos referenced by a URL using Ruby. At this point, I found many related posts, but could not find out how to solve my problem. I tried to use RVideo, but when I do: file = RVideo::Inspector.new(:file => 'http://www.agr

  • Why can't I make a new hash from selected keys in ruby? 2012-02-09

    This has been bugging me for a while. It's not a difficult thing, but I don't know why there's no easy way to do it already, and I bet there is and I don't see it. I just want to take a hash, like this: cars = {:bob => 'Pontiac', :fred => 'Chry

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.211 (s). 11 q(s)