How is it different to declare a variable with and without "@" in Ruby?

Asked

Viewed 255 times

4

What is the difference between these two possibilities?

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

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

Normally in controllers is used with @, but in office each views is usually used without the @, for example.

There are differences in performance?

2 answers

4


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

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

To the each which was quoted follows 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 defined, so it exists only within the block do |post| ... end


To better understand the differences between the types of variables, classes and objects, take a look at this link http://aprendaaprogramar.rubyonrails.com.br/index.rb?Chapter=09.

About the each, look here http://aprendaaprogramar.rubyonrails.com.br/index.rb?Chapter=07

  • Great site you passed. I started learning Rails without mastering 100% Ruby, so some things go unnoticed.

0

It’s like Bruno said the variables without the @ can only be accessed within the scope in which it was created, in which case if you create in the controller, you cannot access the variable in the view.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.