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?
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.
=~ 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.
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"
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