Cal*_*eed 7 ruby regex templates ruby-on-rails
试图在我的一个Rails模型中添加一个非常基本的描述模板.我想要做的是采取这样的模板字符串:
template = "{{ name }} is the best {{ occupation }} in {{ city }}."
Run Code Online (Sandbox Code Playgroud)
和这样的哈希:
vals = {:name => "Joe Smith", :occupation => "birthday clown", :city => "Las Vegas"}
Run Code Online (Sandbox Code Playgroud)
并获得生成的描述.我想我可以用一个简单的gsub做到这一点,但Ruby 1.8.7不接受哈希作为第二个参数.当我像这样做一个gsub作为一个块:
> template.gsub(/\{\{\s*(\w+)\s*\}\}/) {|m| vals[m]}
=> " is the best in ."
Run Code Online (Sandbox Code Playgroud)
您可以看到它用整个字符串(带花括号)替换它,而不是匹配捕获.
如何让它用vals ["something"](或vals ["something".to_sym])替换"{{something}}"?
TIA
Chr*_*ing 24
该字符串格式化操作 %将格式化字符串的哈希作为ARG
>> template = "%{name} is the best %{occupation} in %{city}."
>> vals = {:name => "Joe Smith", :occupation => "birthday clown", :city => "Las Vegas"}
>> template % vals
=> "Joe Smith is the best birthday clown in Las Vegas."
Run Code Online (Sandbox Code Playgroud)
Ruby 1.8.7中的字符串格式化运算符不支持哈希.相反,您可以使用与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", :occupation => "birthday clown", :city => "Las Vegas"}
>> template % vals
=> "Joe Smith is the best birthday clown in Las Vegas."
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3204 次 |
| 最近记录: |