Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 532
LazyJason Avatar asked Mar 26 '10 20:03

LazyJason


2 Answers

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+)

like image 130
Mark Thomas Avatar answered Sep 19 '22 02:09

Mark Thomas


"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"
like image 22
Michael Pilat Avatar answered Sep 21 '22 02:09

Michael Pilat