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

34

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

通常,如果要将一个数组放在循环中,我会这样做。

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

但我想学习其他的替代方案!

1个回答

60
您可以使用方法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

使用两个字符的缩进,而不是四个。


嗨,我知道这已经过时了,但我刚刚在做一些Katas并看到了这篇文章。为什么不应该使用p(如果可能的话,请提供比调试更深入的解释)?此外,我在名为'a'的数组上使用了p aputs a.inspect,只有p a有效。我错过了什么吗? - rorykoehler
我知道在许多 Ruby 开发者中,两个字符的缩进是标准。但是作为一个合法的视力障碍患者,我必须说,2 个字符的缩进对我来说非常不友好。很难看到缩进层次。 - Leonard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接