18
我不確定這個問題是否太愚蠢,但我還沒有找到辦法。Ruby:打印和整齊排列數組的方法
平時要放在一個陣列中的一個循環我這樣做
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
,但我想學其他的替代品!
您好,我知道這是舊的,但我只是在做一些Katas,並遇到這個帖子。爲什麼不應該使用'p'(如果可能,請使用比調試更深的解釋)?我還用'p a'和'把a.inspect'放在一個名爲'a'的數組上,只有'p a'工作。我錯過了什麼嗎? – rorykoehler