Ruby:打印和整理数组的方法

Man*_*nza 26 ruby arrays class puts

我不确定这个问题是否过于愚蠢,但我还没有找到办法.

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

current_humans = [.....]
current_humans.each do |characteristic|
  puts characteristic
end
Run Code Online (Sandbox Code Playgroud)

但是,如果我有这个:

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
Run Code Online (Sandbox Code Playgroud)

它不起作用.

当然我可以使用这样的东西

puts Human.current_humans.inspect
Run Code Online (Sandbox Code Playgroud)

但我想学习其他选择!

Sim*_*tti 50

您可以使用该方法p.使用p实际上相当于在对象上使用puts+ inspect.

humans = %w( foo bar baz )

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

puts humans.inspect
# => ["foo", "bar", "baz"]
Run Code Online (Sandbox Code Playgroud)

但请记住p,更多的是调试工具,它不应该用于在正常工作流程中打印记录.

还有pp(漂亮的印刷品),但你需要先要求它.

require 'pp'

pp %w( foo bar baz )
Run Code Online (Sandbox Code Playgroud)

pp 使用复杂的对象更好.


作为旁注,请勿使用显式返回

def self.print  
  return @@current_humans.to_s    
end
Run Code Online (Sandbox Code Playgroud)

应该

def self.print  
  @@current_humans.to_s    
end
Run Code Online (Sandbox Code Playgroud)

并使用2字符缩进,而不是4.