我不确定这个问题是否太愚蠢了,但我还没有找到解决方法。
通常,如果要将一个数组放在循环中,我会这样做。
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
但我想学习其他的替代方案!
p
(如果可能的话,请提供比调试更深入的解释)?此外,我在名为'a'的数组上使用了p a
和puts a.inspect
,只有p a
有效。我错过了什么吗? - rorykoehler