Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gsub method - accepting hash?

Tags:

ruby

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?

like image 537
Gadi A Avatar asked May 03 '11 16:05

Gadi A


2 Answers

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*"
like image 69
Vasiliy Ermolovich Avatar answered Oct 05 '22 22:10

Vasiliy Ermolovich


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

like image 37
Dylan Markow Avatar answered Oct 05 '22 23:10

Dylan Markow