What's the difference between declaring a variable with and without "@" in Ruby?

4

What's the difference between these two possibilities?

//com @
@post = Post.find(params[:id])

//sem @
post = Post.find(params[:id])

Usually in controllers it is used with @ , but in functions each of views is usually used without @ , for example.

Are there performance differences?

    
asked by anonymous 23.04.2014 / 16:46

2 answers

4

variables that have @ are instance variables in the scope of the current object. the variables without @ are local variables in the scope of the current object.

In the specific case of Rails, the variables with @ used in the controllers are made available to be used "inside" the views.

For the each that was quoted follow the example below:

@posts.each do |post|
  <faz alguma coisa com 'post' aqui>
end

In this code snippet, the variable post is local to the scope of the block in which it was set, so it only exists inside the block do |post| ... end

To better understand the differences between variable types, classes, and objects, take a look at this link link .

About each , look here link

    
23.04.2014 / 17:42
0

This is how Bruno said the variables without the @ can only be accessed within the scope of creation, in case if you create in the controller, you will not be able to access the variable in the view.

    
17.03.2015 / 17:38