开发者

Ruby gsub method - accepting hash?

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 matc开发者_如何学Ched 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


"hello".gsub( /([eo])/ ){ {'e' => 3, 'o' => '*'}[$1] }


You may want to see if backports will enable the 1.9.2 functionality in 1.8.7.


Add this to the Hash class of your project:

# replaces recursively old_value by new_value
def gsub_hash_values(old_value, new_value)
  self.each do |k, v|
    if v.is_a?(Array)
      v.each do |vv|
        vv.gsub!(old_value, new_value)
      end
    elsif v.is_a?(Hash)
      v.gsub_hash_values(old_value, new_value)
    elsif v.respond_to?(:to_s)
     self[k] = v.to_s.gsub(old_value, new_value)
    end
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜