감사합니다. 부모, 자녀 및 모듈이 두 개의 개별 파일에 있습니다. player_fabrizio
은 의 하위 클래스 인 Player
클래스의 인스턴스입니다. 인스턴스 player_fabrizio
은 인스턴스 new_settings
의 @totalmoney
변수를 사용해야합니다.Ruby - Mixins을 사용하여 모듈에서 계산 된 부모 변수를 얻으십시오
require_relative "modules_test"
class Settings
include Variables
attr_reader :totalmoney
end
class Player < Settings
def initialize(kingdom, king)
@playerData = [kingdom, king]
end
def calculate
print @totalmoney
end
end
new_settings = Settings.new
new_settings.globalSettings(100, 2)
player_fabrizio = Player.new("MyDinasty", "Fabrizio")
player_fabrizio.calculate # no output
이것은 modules_test.rb 파일입니다. new_setting
은 globalSettings
이 module Variables
이고 @totalmoney
변수를 설정합니다.
module Variables
def globalSettings(totalmoney, nplayer)
@totalmoney = totalmoney
return @totalmoney
end
end
player_fabrizio.calculate
의 결과는 100이어야하지만 대신 출력이 제공되지 않습니다. 포럼을 검색했지만 질문을 찾을 수 없었습니다. 비슷한 문제가있는 질문을 읽었지만 답을 찾을 수 없었습니다.
고마워요 당신은 파브리 지오
(Ruby, mixin instance variables and methods)
여기서 부모 클래스로부터 변수를 가져 오려고하지 않습니다. 대신 부모 클래스 –
'@ total_money'의 다른 객체로부터 가져 오기를 시도하면 클래스 자체가 아니라 인스턴스화 된 객체에 저장됩니다. 'new_settings'는'Settings' 클래스의 인스턴스이고'player_fabrizio'는'new_settings' 객체를 알지 못하는'Player' 클래스의 인스턴스입니다. – lcguida