Rob Heiser Rob Heiser - 1 year ago 85
Ruby Question

How can I use a regex match as a hash index in Ruby?

I'm new to Ruby and I've run into an issue I can't solve.

I'm trying to use

to match a pattern in a string, then use that match as an index into a hash. So far, I haven't been able to figure it out. Here's some code:

farm = { "pig_num" => 5, "horse_num" => 2, "cow_num" => 4}
assessment = "There are 'pig_num' pigs on this farm"

assessment.gsub(/'(.+?)'/, '\1') # => "There are pig_num pigs on this farm"
assessment.gsub(/'(.+?)'/, farm) # => "There are pigs on this farm"
assessment.gsub(/'(.+?)'/, farm['\1']) # => TypeError: no implicit conversion of nil into String
assessment.gsub(/'(.+?)'/) { |key| farm[key] }

The first call to
shows that I am matching the string I want.

The second call is an attempt to use the
gsub(pattern, hash)
flavor found at the Ruby documentation site.

The third call is trying to reference the value using the match as an index.

The fourth is some fancy pants way I thought might work using a lambda/proc/block.

What am I doing wrong?

Answer Source

Try this

assessment.gsub(/#{farm.keys.join('|')}/, farm)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download