【问题标题】:Ruby: method to print and neat an arrayRuby:打印和整理数组的方法
【发布时间】:2013-03-24 22:49:33
【问题描述】:

我不确定这个问题是不是太傻了,但我还没有找到办法。

通常我会在循环中放置一个数组

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

但我想学习其他替代方法!

【问题讨论】:

    标签: ruby arrays class puts


    【解决方案1】:

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

    【讨论】:

    • 嗨,我知道这是旧的,但我只是在做一些 Katas 并遇到了这篇文章。为什么不应该使用p(如果可能,请比调试更深入的解释)?我还在一个名为“a”的数组上使用了p aputs a.inspect,只有p a 有效。我错过了什么吗?
    • 我知道 2 个字符的缩进是很多 ruby​​ 世界的标准。作为一个合法失明的人,我不得不说 2 个字符的缩进让我很失望。很难看到缩进级别。
    最近更新 更多