Ruby: 인스턴스 및 클래스 메서드의 SELF
                                            
                                                
                                                
                                                
                                                
                                                
                                                 6690 단어  rubybeginnersprogramming
                    
인스턴스 메서드의 자체
Ruby는 OOP 때문에 객체를 식별하기 위해 클래스를 사용합니다. 클래스는 유사한 특성을 가진 개체를 만들기 위한 템플릿 또는 청사진과 같습니다. 클래스를 만들 때 해당 클래스의 각각의 새 인스턴스를 객체라고 합니다. 이 개체는 데이터와 동작을 모두 포함하는 코드 묶음입니다. 각 클래스 내에서 개발자는 수많은 인스턴스 메서드를 만들 수 있습니다.
class Game
  attr_accessor :name
  def initialize
    @name = name
  end
  def developer_of_game(name, developer_name)
    name.developer = developer_name
  end
end
위의 예에서는
attr_accessor 속성을 변경하기 위해 name 매크로를 사용합니다. #developer_of_game 인스턴스 메서드는 Game의 개체를 가져와 해당 인스턴스에 이름을 할당합니다. 그러나 self 를 사용하여 동일한 결과를 얻을 수 있는 더 쉽고 DRY-er 방법이 있습니다. self는 메서드가 호출되는 모든 인스턴스를 나타냅니다.class Game
  attr_accessor :name
  def initialize
    @name = name
  end
  def developer_of_game(developer_name)
    self.developer = developer_name
  end
end
elden_ring = Game.new('Elden Ring')
elden_ring.developer_of_game('FromSoftware')
elden_ring.developer
# => 'FromSoftware'
인스턴스 메소드 내부에
self를 배치함으로써 메소드는 우리가 생성한 특정 객체를 가져와서 메소드에 적용합니다. self 를 출력하면 클래스의 인스턴스이고 고유한 객체임을 알 수 있습니다.class Game
  attr_accessor :name
  def initialize
    @name = name
  end
  def print_out_self
    puts self
  end
end
elden_ring = Game.new('Elden Ring')
elden_ring.print_out_self
# => #<Game:0x00007fd9910c45a0 @name='Elden Ring'>
수업 방식의 자기
클래스 메서드에도
self를 사용할 수 있습니다. 마지막 예에서 self를 사용하여 클래스 메서드를 만들 수 있습니다.class Game
  attr_accessor :name
  @@all = []
  def initialize
    @name = name
    @@all << self
  end
  def developer_of_game(developer_name)
    self.developer = developer_name
  end
  def self.all
    @@all
  end
end
elden_ring = Game.new('Elden Ring')
dead_space = Game.new('Dead Space')
Game.all
# => [#<Game:0x00007fd9910c45a0 @name='Elden Ring'>, #<Game:0x00007fd9900dba58 @name='Dead Space'>]
참고:
self 메서드 내부의 #developer_of_game는 self의 self.all와 동일하지 않습니다.Game.all는 모든 Game의 배열을 생성합니다. @@all는 초기에 빈 배열[]로 설정되는 클래스 변수입니다. 초기화 방법에서 각 개별 인스턴스의 self가 @@all 변수에 삽입됩니다. self.all 클래스 메서드가 호출되면 해당 메서드가 클래스의 한 인스턴스가 아니라 전체 클래스에서 호출되기 때문에 생성된 Game 클래스의 모든 인스턴스가 해당 배열에 포함됩니다. 마지막으로 @@all 내부에서 self.all 클래스 변수를 호출해야 읽을 수 있습니다. 각 게임의 이름만 가져오려면 다른 클래스 메서드 내에서 방금 정의한 클래스 메서드.each를 사용할 수 있습니다.def self.print_all_game_names
    self.all.each do |game|
      puts game.name
    end
end
결론
self.all와 관련하여 기억해야 할 가장 중요한 사항: 인스턴스 메서드 내에서 self를 사용할 때 메서드가 호출되는 것은 해당 클래스의 객체 중 하나입니다. 클래스 메서드에서 self를 사용하는 경우 전체 클래스 자체입니다.
                Reference
이 문제에 관하여(Ruby: 인스턴스 및 클래스 메서드의 SELF), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/rossonevan/ruby-self-in-instance-and-class-methods-4j3g텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)