루비로 확장
클래스에서 클래스로, 함수에서 함수로 참조하는 것은 객체 지향 프로그래밍에서 일반적인 작업입니다. 다른 클래스에서 모듈을 가져오는 방법을 찾고 있다면 이 문서가 도움이 될 수 있습니다.
Ruby에서는 두 가지 방법으로 이 작업을 수행할 수 있습니다. include 또는 extend를 사용합니다.
이 기사에서는 Ruby의 include 및 extend에 대해 논의하고 주제를 더 쉽게 만들기 위해 관련 예제를 살펴봅니다.
Ruby에서 “포함"이란 무엇입니까?
include를 사용하면 코드 모듈을 가져올 수 있습니다. 클래스를 통해 모듈을 직접 가져오는 방법을 얻으려고 하면 슈퍼클래스에 대한 하위 클래스로 가져오기 때문에 오류가 발생합니다.
여기서 해결책은 클래스의 인스턴스로 가져오는 것입니다. include 키워드를 사용하여 include를 사용할 수 있습니다.
Ruby에서 확장이란 무엇입니까?
모듈을 가져오는 또 다른 방법은 extend 키워드를 사용하는 것입니다. extend를 통해 메서드를 클래스 메서드로 가져올 수 있습니다.
그러나 인스턴스를 통해 가져온 모듈의 메서드를 가져오려고 하면 오류가 발생합니다. 이 오류를 방지하려면 클래스 정의에서 해당 메서드를 가져와야 합니다.
Ruby에서 include 및 extend 사용
아래 예에서는 Ruby에서 include 및 extend 키워드의 사용을 설명합니다. 아래 예제 코드를 살펴보십시오.
module MyModule def MyMethod puts 'DelftStack is nice.' end end class ClassA # only can access MyModule methods # By the instance. include MyModule end class ClassB # only can access MyModule methods # By the class definition. extend MyModule end # Access from the object ClassA.new.MyMethod # Acess from class ClassB.MyMethod 각 줄의 목적은 주석 처리되고 include 및 extend 키워드의 작동 메커니즘에 대해 설명합니다. 위의 예제 코드를 실행하면 아래와 같은 결과를 얻을 수 있습니다.
DelftStack is nice. DelftStack is nice. 이제 아래와 같이 클래스에서 직접 메서드에 액세스하려고 하면 다음과 같습니다.
ClassA.MyMethod 아래와 같은 오류가 표시됩니다.
# NoMethodError: undefined method # `MyMethod' for ClassA:Class ClassA는 include 키워드를 사용하는 모듈을 포함하고 include는 클래스에서 직접 메서드를 호출할 수 없기 때문입니다.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn