简体   繁体   中英

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

#{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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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