Intermingling attr_accessor and an initialize method in one class

后端 未结 4 1526
梦毁少年i
梦毁少年i 2021-01-30 02:59

I see code like:

class Person
  def initialize(name)
    @name = name
  end
end

I understand this allows me to do things like person = Pe

4条回答
  •  不知归路
    2021-01-30 03:23

    Unlike C++,Java instance variables in Ruby are private by default(partially as they can be accessed by using a.instance_variable_get :@x)

    eg:

      class Dda
        def initialize task
            @task = task
            @done = false
        end
      end
    item = Dda.new "Jogging" # This would call the initializer and task = Jogging would
    be set for item
    item.task # would give error as their is no function named task to access the instance
    variable.
    

    Although we have set the value to item but we won't be able to do anything with it as instace variables are private in ruby. code for getter:

    def task
      @task
    end
    #for getter
    def task=task
       @task = task
    end
    

    Using getter would ensure that item.task returns it's value And using setter gives us the flexibility to provide values to instance variables at any time.

提交回复
热议问题