Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby 1.9 regex as a hash key

Tags:

regex

ruby

hash

I am trying this example myhash = {/(\d+)/ => "hello"} with ruby 1.9.2p136 (2010-12-25) [i386-mingw32].
It doesn't work as expected (edit: as it turned out it shouldn't work as I was expecting):

irb(main):004:0> myhash = {/(\d+)/ => "hello"}
=> {/(\d+)/=>"Hello"}
irb(main):005:0> myhash[2222]
=> nil
irb(main):006:0> myhash["2222"]
=> nil

In Rubular which is on ruby1.8.7 the regex works.
What am I missing?

like image 517
Mr. L Avatar asked Mar 15 '11 11:03

Mr. L


People also ask

How do you make Hash 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.

What does =~ mean in Ruby?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.


1 Answers

You can put Jean's answer in a default_proc

MAP = {
  /1/ => "one",
  /2/ => "two",
  /\d/ => "number"
}

MAP.default_proc = lambda do |hash, lookup|
  hash.each_pair do |key, value|
    return value if key =~ lookup
  end
  return nil
end

p MAP["2"] #=> "two"
p MAP[44] #=> "number"
like image 141
Voxar Avatar answered Sep 17 '22 12:09

Voxar