29

我不确定这个问题是否太愚蠢,但我还没有找到解决方法。

通常将数组放入循环中,我这样做

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

但我想学习其他选择!

4

1 回答 1

55

你可以使用方法p。usingp实际上等同于在对象上使用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-chars 缩进,而不是 4。

于 2013-04-03T10:14:21.267 回答