繁体   English   中英

Ruby字符串#{}不起作用

[英]Ruby String #{} doesn't work

我有这是我的代码:

class Template
  def initialize(temp_str)
    @str = temp_str
  end

  def render options={}
    @str.gsub!(/{{/,'#{options[:').gsub!(/}}/,']}')
    puts @str
  end
end

template = Template.new("{{name}} likes {{animal_type}}")
template.render(name: "John", animal_type: "dogs")

我希望结果是John likes dogs ,但是那是

#{options[:name]} likes #{options[:animal_type]}

为什么不插入#{}

#{}并不是某种魔术,它每当发生时都会转换为插值。 这是内插的字面语法。 在这里,您并不是按字面意思来编写它,而是可以通过替换获得它。 相反,您可以执行以下操作:

template = "{{name}} likes {{animal_type}}"
options  = {name: 'John', animal_type: 'dogs'}
template.gsub(/{{(.*?)}}/) { options[$1.to_sym] } # => "John likes dogs"

这将捕获胡须内的名称并使用其索引哈希。


更好的办法是利用现有的格式功能 使用%{}代替小胡子:

template = "%{name} likes %{animal_type}"
options  = {name: 'John', animal_type: 'dogs'}
template % options # => "John likes dogs"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM