【发布时间】:2013-03-24 22:49:33
【问题描述】:
我不确定这个问题是不是太傻了,但我还没有找到办法。
通常我会在循环中放置一个数组
current_humans = [.....]
current_humans.each do |characteristic|
puts characteristic
end
但是,如果我有这个:
class Human
attr_accessor:name,:country,:sex
@@current_humans = []
def self.current_humans
@@current_humans
end
def self.print
#@@current_humans.each do |characteristic|
# puts characteristic
#end
return @@current_humans.to_s
end
def initialize(name='',country='',sex='')
@name = name
@country = country
@sex = sex
@@current_humans << self #everytime it is save or initialize it save all the data into an array
puts "A new human has been instantiated"
end
end
jhon = Human.new('Jhon','American','M')
mary = Human.new('Mary','German','F')
puts Human.print
它不起作用。
我当然可以使用这样的东西
puts Human.current_humans.inspect
但我想学习其他替代方法!
【问题讨论】: