Ruby's gsub string method is supposed to accept hash. As written here:
http://www.ruby-doc.org/core/classes/String.html#M001185
"If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string."
They give an example:
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"
Problem is, it's not working for me (ruby 1.8.7):
in `gsub': can't convert Hash into String (TypeError)
This happens for the exact same line. Why?
It's because the doc that OP mentions is for ruby 1.9.2
. For ruby 1.8.7
, refer to http://www.ruby-doc.org/core-1.8.7/classes/String.html#M000792; there, gsub
method does not accept hash as param.
UPDATE: You can add this feature to your code:
class String
def awesome_gsub(pattern, hash)
gsub(pattern) do |m|
hash[m]
end
end
end
p 'hello'.awesome_gsub(/[eo]/, 'e' => '3', 'o' => '*') #=> "h3ll*"
This is a Ruby 1.9-specific feature.
The Ruby 1.8.7 documentation makes no mention of it: http://www.ruby-doc.org/core-1.8.7/classes/String.html
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