简体   繁体   中英

Why are @ variables used in Ruby class models?

Why are @variables needed in classes? What value do they add? I couldn't find anything online for this but maybe I'm searching for the wrong terms. Is there a resource online I can look this up? Thanks!

car.rb

class Car
  attr_accessor :make, :model

  def initialize(make = '')
    @make = ''
    @model = ''
  end
end

These variables are called instance variables. Every instance of the class has it's own copy of these variables.

In your example, you would like every instance of the class Car to have it's own make and model.

Note the following example

car1 = Car.new("Toyota", "Carola")
car2 = Car.new("Mitsubishi", "Lancer")

Both car1 and car2 each have their own private make and model . The way to tell the Ruby interpreter to do this is to use @.

这是在ruby中定义实例变量的语法。

Instance variables are available in all areas of each instance of a class.

Each time you create an instance of car the variable is specific to that particular one.

eg

car1 = Car.new('Ford', 'Falcon')
car2 = Car.new('Toyota', 'Camry')

Now car1 and car2 have different instances of @make and @model.

If you declare the variable as a class variable using @@make , then every Car has access to it and every time it is changed, it is changed for everyone.

Basically class variables allow you to put some 'walls' around your data.

The attr_accessor creates two methods in your call

def make=(value)
@make = value
end

def make
@make
end

This allows you to call the instance variable within and from outside your class without the @

eg

car1.make

returns

'Ford'

www.codecademy.com has some great free courses in basic Ruby that will teach you this stuff really well.

Objects are said to have behaviours and properties, much like real world object. The properties of objects are defined by instance variables. And @ prefix is ruby's way of telling particular variable is an instance variable/characteristic.

What value they add ?

They help you to have a variable that is accessible across all your instance methods.

Let us disect your example

   class Car
    attr_accessor :make, :model #attr_accessor methods creates a getter method.    car_instance.make and
                 #a setter method car_instance.make=(val), which otherwise you would have to do explicitly. 

    def initialize(make = '')   #constructor
      @make = '' #initializing your instance variables. I guess you meant @make = make here     
      @model = ''
    end
   end

I couldn't find anything online for this but maybe I'm searching for the wrong terms.

Yup you were.

Is there a resource online I can look this up?

Yup, Ruby User Guide By Matz

Bit more details

In ruby, the scope of a variable inside a class is identified by the compiler by first two characters of the varaible name.

  • @@variable_name -> Two '@' s. Class variables/ Scope across all instances of the class. Eg: If you want to have a count on total number of cars you made.

  • @variable -> One '@' Instance varaibles/ Scope across an instance.

  • variable -> No '@' Local variables/ Scope to the block they belong.

Look at the below code,which I changed a bit for understanding:

class Car
  attr_accessor :make, :model

  def initialize(make = '')
    @make = make
    @model = ''
  end
end

car1 = Car.new("Toyota")
car2 = Car.new("Roxin")
p car1.instance_variables #<~~ A
p car2.instance_variables #<~~ B
p car1 #<~~C
p car2#<~~D

Output:

[:@make, :@model]
[:@make, :@model]
#<Car:0x1bc89e8 @make="Toyota", @model="">
#<Car:0x1bc8940 @make="Roxin", @model="">

Explanation: Here in A and B you might think of that both car1,car2 are using the same copy of instance variables. But Not is the case. See when I am printing car1 and car2, in C and D ,outputs shows that car1 and car2 are holding different values for the instance variable @make . This fact objects has their own unique instance variables.

Hope this helps.

Cheers!!

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