Merge a hash with the key/values of a string in ruby

Posted by LazyJason on Stack Overflow See other posts from Stack Overflow or by LazyJason
Published on 2010-03-26T20:22:53Z Indexed on 2010/03/26 20:43 UTC
Read the original article Hit count: 215

Filed under:
|
|
|

Hi there,

I'm trying to merge a hash with the key/values of string in ruby.

i.e.

h = {:day => 4, :month => 8, :year => 2010}
s = "/my/crazy/url/:day/:month/:year"
puts s.interpolate(h)

All I've found is to iterate the keys and replace the values. But I'm not sure if there's a better way doing this? :)

class String
  def interpolate(e)
    self if e.each{|k, v| self.gsub!(":#{k}", "#{v}")}
  end
end

Thanks

© Stack Overflow or respective owner

Related posts about ruby

Related posts about hash