简体   繁体   中英

Ruby variables vs instance variables in Sinatra

In Sinatra you can declare variables in two ways; either:

get '/' do
    var = 5
end

or

get '/' do
    @var = 5
end

Why use one or the other?

Also, shouldn't you technically not be able to use @ , since it is not within a class, therefore an instance variable does not make sense?

Instance variables are setted on object, you are right.

But you can use them also on classes for example, because they are also objects. This might be hard to understand, but in ruby everything is an object, so because of that you can set instance variables everywhere (almost?).

When you call sinatra 'get' method. You are passing a block that should be run inside an object context. That you can later use inside your views for example.

get '/' do
  @var = 5
end

I'm not sure which one you should use, I would stick with instance @variables if you need them in the view, and local variables if you just want to use them inside the action/route

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