views:

124

answers:

3

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

+5  A: 

"Better" is probably subjective, but here's a method using only one call to gsub:

class String
  def interpolate!(h)
    self.gsub!(/:(\w+)/) { h[$1.to_sym] }
  end
end

Thus:

>> "/my/crazy/url/:day/:month/:year".interpolate!(h)
=> "/my/crazy/url/4/8/2010"
Michael Pilat
but what happens if you have `s="/my/crazy/url/:somethingelse/:month/:year"`?
gnibbler
Well, `h[:nothashed]` gives `nil`, so it would replace with an empty string. You can fix that with something like `h[$1.to_sym]||"default"`
Michael Pilat
+1  A: 

That doesn't look bad to me, but another approach would be to use ERB:

require 'erb'

h = {:day => 4, :month => 8, :year => 2010}
template = ERB.new "/my/crazy/url/<%=h[:day]%>/<%=h[:month]%>/<%=h[:year]%>"
puts template.result(binding)
JacobM
+1  A: 

Additional idea could be to extend String#% method so that it know how to handle Hash parameters, while keeping existing functionality:

class String
  alias_method :orig_percent, :%
  def %(e)
    if e.is_a?(Hash)
      # based on Michael's answer
      self.gsub(/:(\w+)/) {e[$1.to_sym]}
    else
      self.orig_percent e
    end
  end
end

s = "/my/%s/%d/:day/:month/:year"
puts s % {:day => 4, :month => 8, :year => 2010}
#=> /my/%s/%d/4/8/2010
puts s % ['test', 5]
#=> /my/test/5/:day/:month/:year
Mladen Jablanović
Thank you Mladen. This looks really promising
LazyJason