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
No need to reinvent Ruby built-ins:
h = {:day => 4, :month => 8, :year => 2010}
s = "/my/crazy/url/%{day}/%{month}/%{year}"
puts s % h
(Note this requires Ruby 1.9+)
"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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With