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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15784503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:51:49  来源:igfitidea点击:

Ruby: method to print and neat an array

rubyarraysclassputs

提问by Manza

I am not sure if this question is too silly but I haven't found a way to do it.

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

Usually to puts an array in a loop I do this

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

current_humans = [.....]
current_humans.each do |characteristic|
  puts characteristic
end

However if I have this:

但是,如果我有这个:

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

It doesn't work.

它不起作用。

Of course I can use something like this

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

puts Human.current_humans.inspect

but I want to learn other alternatives!

但我想学习其他选择!

回答by Simone Carletti

You can use the method p. Using pis actually equivalent of using puts+ inspecton an object.

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

humans = %w( foo bar baz )

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

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

But keep in mind pis more a debugging tool, it should not be used for printing records in the normal workflow.

但请记住p,它更像是一个调试工具,不应用于正常工作流程中的打印记录。

There is also pp(pretty print), but you need to require it first.

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

require 'pp'

pp %w( foo bar baz )

ppworks better with complex objects.

pp处理复杂的对象效果更好。



As a side note, don't use explicit return

作为旁注,不要使用显式返回

def self.print  
  return @@current_humans.to_s    
end

should be

应该

def self.print  
  @@current_humans.to_s    
end

And use 2-chars indentation, not 4.

并使用 2 个字符的缩进,而不是 4 个。