我想在Ruby中将哈希与字符串的键/值合并。
例如:
h = {:day => 4, :month => 8, :year => 2010}
s = "/my/crazy/url/:day/:month/:year"
puts s.interpolate(h)
我找到的方法是迭代键并替换值。但我不确定是否有更好的方法来做这件事? :)
class String
def interpolate(e)
self if e.each{|k, v| self.gsub!(":#{k}", "#{v}")}
end
end
谢谢