ruby class collections
how does this work?
in irb:
>&g开发者_如何学Pythont; class A
>> b = [1, 2,3]
>> end
=> [1, 2, 3]
Is b an instance variable? class variable? how would I access b from outside the class? Is it used for meta-programming?
Is b an instance variable? class variable?
No, it's a local variable inside the class ... end
scope.
how would I access b from outside the class?
You wouldn't. It goes out of scope (and is thus inaccessible) once it reaches the end
.
Is it used for meta-programming?
It can be. Example:
class A
b = [1,2,3]
b.each do |i|
define_method("foo#{i}") do end
end
end
I've now defined the methods foo1, foo2 and foo3.
Of course this wouldn't behave any differently if I didn't create the variable b and just did [1,2,3].each
directly. So creating a local variable by itself does nothing, it allows you to write cleaner code (the same as using local variables in a method).
b is a simple block variable, you cannot access it from outside of the block.
You can use class like this :
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
@@count=@@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
精彩评论