Ruby/Sinatra - Variable inside erb calls

Hi there,

I have a question regarding variables inside of erb arguments. This is
what I would like to achieve:

require ‘sinatra’

get ‘/’ do
style = ‘default’
erb :‘templates/’+style+’/layout’
end

Running that will give you errors, saying there can’t be a plus sign for
the concatenation.

Is there a way to work around this?

You are on the right track:

:~> $ irb
ruby-1.9.2-p0 > :“hello”+‘world’
NoMethodError: undefined method +' for :hello:Symbol from (irb):1 from /home/eugenc/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in
ruby-1.9.2-p0 > x = “hello”+‘world’
=> “helloworld”
ruby-1.9.2-p0 > :x
=> :x
ruby-1.9.2-p0 >

In your case ruby converted :‘templates/’ to symbol, then tried to
concatenate string to it, this is because ‘:’ has higher priority then
‘+’ operator. Solution is

template_name = ‘templates/’+style+’/layout’
erb template_name

(drop ‘:’ operator, it is not necessary).


http://blog.eugen.co

Eugen C. wrote in post #999234:

(drop ‘:’ operator, it is not necessary).

According to the Sinatra docs, it must be a symbol. So I would just use
string interpolation:

erb :“templates/#{style}/layout”

Or if you must do things the hard way, you can use the much uglier:

erb (‘templates/’+style+’/layout’).to_sym

Note that when you use string interpolation, you create only one string.
However, when you use this construct:

‘templates/’+style+’/layout’

First, you create the string ‘templates/’ and then the string ‘/layout’,
and then you concatenate them with the style variable, to create a third
string. Therefore, you should prefer string interpolation over string
concatenation.

Thank you both for the help, it works perfectly and I now understand why
it wasn’t working before :smiley:

<3 this forum

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs