How can I use a regex match as a hash index in Ruby? -
i'm new ruby , i've run issue can't solve.
i'm trying use gsub()
match pattern in string, use match index hash. far, haven't been able figure out. here's code:
farm = { "pig_num" => 5, "horse_num" => 2, "cow_num" => 4} assessment = "there 'pig_num' pigs on farm" assessment.gsub(/'(.+?)'/, '\1') # => "there pig_num pigs on farm" assessment.gsub(/'(.+?)'/, farm) # => "there pigs on farm" assessment.gsub(/'(.+?)'/, farm['\1']) # => typeerror: no implicit conversion of nil string assessment.gsub(/'(.+?)'/) { |key| farm[key] }
the first call gsub()
shows matching string want.
the second call attempt use gsub(pattern, hash)
flavor found @ the ruby documentation site.
the third call trying reference value using match index.
the fourth fancy pants way thought might work using lambda/proc/block.
what doing wrong?
try this
assessment.gsub(/#{farm.keys.join('|')}/, farm)
Comments
Post a Comment