ruby initialize method - purpose of initialize arguments

时间:2019-01-18 18:33:02

标签: ruby oop initialization arguments

Im a bit confused on the initialize method. I understand that it is automatically called when you do Person.new and you add the arguments to it like Person.new("james"). What I dont understand is, why would you have instance variables in your initialize method that are not an used as an argument also. Is it so you can use them later on after the instance has been created? See below. What reason is there to have @age in the initialize method but not as an argument. thanks.

class Person

  attr_accessor :name, :age

  def initialize(name)
    @name = name
    @age = age
  end

3 个答案:

答案 0 :(得分:0)

The instance variables declared inside your initialize method only need to be those which you want to set during initialization. In your Person class example, you wouldn't need to set @age in initialization (it actually would throw an error as you currently have it).

  class Person

    attr_accessor :name, :age

    def initialize(name)
      @name = name
    end

    def birthday
      if @age.nil?
        @age = 1
      else
        @age += 1
      end
    end
  end

Hopefully, this helps. If the initialize method doesn't have an age set, you can still use/set age in other methods. In this case, the first time the Person.birthday method is called, it would set their @age to 1, and then increment it from there.

答案 1 :(得分:0)

您可以在类中的任何方法中设置实例变量。

initialize是一种在调用Person.new之后立即执行的方法。

对象的所有外部数据都通过.new(args)的参数传递。

您的行@age = age-与@age = nil相同。

这是由于age的参数中没有initialize

您还有attr_accessor :age

等于,您拥有方法:

def age
  @age
end

def age=(age)
  @age = age
end

因此您可以这样设置实例变量:

john = Person.new('John')
p john.age #=> nil

john.age = 5
p john.age #=> 5

答案 2 :(得分:0)

例如,如果您需要在实例化对象时调用方法为实例变量分配值。

这很愚蠢,但是给出了一个主意:

class Person

  attr_accessor :name, :age

  def initialize(name)
    @name = name
    @age = random_age
  end

  def random_age
    rand(1..100)
  end

end

jack = Person.new('jack')
p jack.age #=> 29