简体   繁体   English

Ruby字符串#{}不起作用

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

I have this is my code: 我有这是我的代码:

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

I was hoping the result would be John likes dogs , but it was 我希望结果是John likes dogs ,但是那是

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

Why doesn't the #{} get interpolated? 为什么不插入#{}

#{} is not some magic that gets converted to interpolation whenever it occurs. #{}并不是某种魔术,它每当发生时都会转换为插值。 It's a literal syntax for interpolating. 这是内插的字面语法。 Here you are not writing it literally, you get it by doing a replacement. 在这里,您并不是按字面意思来编写它,而是可以通过替换获得它。 Instead, you could do something like: 相反,您可以执行以下操作:

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

This captures the name inside the moustaches and indexes the hash with it. 这将捕获胡须内的名称并使用其索引哈希。


Even better would be to utilize the existing format functionality . 更好的办法是利用现有的格式功能 Instead of moustaches, use %{} : 使用%{}代替小胡子:

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