어떻게 작동하나요? IRB에루비 클래스 모음
:
>> class A
>> b = [1, 2,3]
>> end
=> [1, 2, 3]
는 인스턴스 변수를 B? 클래스 변수? 수업 외부에서 의 b에 어떻게 액세스합니까? 메타 프로그래밍에 사용됩니까?
어떻게 작동하나요? IRB에루비 클래스 모음
:
>> class A
>> b = [1, 2,3]
>> end
=> [1, 2, 3]
는 인스턴스 변수를 B? 클래스 변수? 수업 외부에서 의 b에 어떻게 액세스합니까? 메타 프로그래밍에 사용됩니까?
인스턴스 변수는 무엇입니까? 클래스 변수?
아니요, 로컬 변수는 class ... end
입니다.
클래스 외부에서 b에 어떻게 액세스합니까?
그렇지 않을 수도 있습니다. end
에 도달하면 범위를 벗어나 (따라서 액세스 할 수 없게됩니다.)
메타 프로그래밍에 사용됩니까?
될 수 있습니다. 예 :
class A
b = [1,2,3]
b.each do |i|
define_method("foo#{i}") do end
end
end
이제 foo1, foo2 및 foo3 메서드를 정의했습니다.
물론 변수 b를 만들지 않고 그냥 [1,2,3].each
을 실행하면이 동작이 다르게 작동하지 않습니다. 따라서 로컬 변수를 단독으로 생성하면 아무 일도 일어나지 않으므로 메서드에서 로컬 변수를 사용하는 것과 동일한 코드를 작성할 수 있습니다.
b는 간단한 블록 변수이므로 블록 외부에서 액세스 할 수 없습니다. 이 같은 클래스를 사용할 수 있습니다
:
class Building
@@count=0 #This is a class variable
MIN_HEIGHT=50 #This is a constant
attr_accessor :color, :size #grant access to instance variables
def initialize options
@color=options[:color] #@color is an instance variable
@size=options[:size] #@size too
@@[email protected]@count+1
end
def self.build options #This is a class method
# Adding a new building
building=Building.new options
end
end
#[...]
Building.build({:color=>'red', :size=>135})
blue_building=Building.new({:color=>'blue', :size=>55})
puts blue_building.color # How to use an instance variable
# => 'blue'
puts "You own #{Building.count.to_s} buildings !" # How to use a class variable
# => 'You own 2 buildings !'
puts Building::MIN_HEIGHT # How to use a constant
# => 50
당신은'Building.build'가 아닌'Building.add'을 찾으시는 것입니까? –
고마워, 그게 더 좋다 : P – Cicatrice