试图在我的一个Rails模型中添加一个非常基本的描述模板.我想要做的是采取这样的模板字符串:
template = "{{ name }} is the best {{ occupation }} in {{ city }}."
和这样的哈希:
vals = {:name => "Joe Smith",:occupation => "birthday clown",:city => "Las Vegas"}
并获得生成的描述.我以为我可以用一个简单的gsub做到这一点但Ruby 1.8.7不接受哈希作为第二个参数.当我像这样做一个gsub作为一个块:
> template.gsub(/\{\{\s*(\w+)\s*\}\}/) {|m| vals[m]} => " is the best in ."
您可以看到它用整个字符串(带花括号)替换它,而不是匹配捕获.
如何让它用vals [“something”](或vals [“something”.to_sym])替换“{{something}}”?
TIA
解决方法
使用Ruby 1.9.2
string formatting operator%将使用散列格式化字符串作为arg
>> template = "%{name} is the best %{occupation} in %{city}." >> vals = {:name => "Joe Smith",:city => "Las Vegas"} >> template % vals => "Joe Smith is the best birthday clown in Las Vegas."
使用Ruby 1.8.7
The string formatting operator in Ruby 1.8.7 doesn’t support hashes.相反,您可以使用与Ruby 1.9.2解决方案相同的参数并修补String对象,因此在升级Ruby时,您不必编辑字符串.
if RUBY_VERSION < '1.9.2' class String old_format = instance_method(:%) define_method(:%) do |arg| if arg.is_a?(Hash) self.gsub(/%\{(.*?)\}/) { arg[$1.to_sym] } else old_format.bind(self).call(arg) end end end end >> "%05d" % 123 => "00123" >> "%-5s: %08x" % [ "ID",123 ] => "ID : 0000007b" >> template = "%{name} is the best %{occupation} in %{city}." >> vals = {:name => "Joe Smith",:city => "Las Vegas"} >> template % vals => "Joe Smith is the best birthday clown in Las Vegas."