2013-04-03 39 views
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 

,但我想學其他的替代品!

回答

36

您可以使用該方法p。使用p實際上等效於在對象上使用puts + inspect

humans = %w(foo bar baz) 

p humans 
# => ["foo", "bar", "baz"] 

puts humans.inspect 
# => ["foo", "bar", "baz"] 

但是要記住p更多的是一種調試工具,它不應該在正常的工作流程用於打印記錄。

還有pp(代碼),但你必須要求它第一。

require 'pp' 

pp %w(foo bar baz) 

pp對於複雜的物體效果更好。


作爲一個側面說明,不要用明確的返回

def self.print 
    return @@current_humans.to_s  
end 

應該

def self.print 
    @@current_humans.to_s  
end 

而且使用2個字符縮進,而不是4

+0

您好,我知道這是舊的,但我只是在做一些Katas,並遇到這個帖子。爲什麼不應該使用'p'(如果可能,請使用比調試更深的解釋)?我還用'p a'和'把a.inspect'放在一個名爲'a'的數組上,只有'p a'工作。我錯過了什麼嗎? – rorykoehler