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

标签 ruby arrays class puts

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

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

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

但我想学习其他选择!

最佳答案

您可以使用方法p。使用 p 实际上等同于对对象使用 puts + inspect

humans = %w( foo bar baz )

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

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

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

还有 pp( pretty-print ),但你需要先要求它。

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 个。

关于Ruby:打印和整理数组的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15784503/

相关文章:

ruby - 将鞋子集成到 Aptana Studio RadRails 中

ruby-on-rails - 存储数据库中引用的常量的最佳方式?

ruby - 缓存获取的网页有哪些选项?

java - 根据字符串大小(长度)对字符串数组进行排序

jQuery - 查找类中的所有 ID

ruby-on-rails - 在单独的服务器上设置 resque/redis

javascript - 对象在 react render() 内部似乎是空的,即使之前的日志记录证明它不是

c - 获取用户输入并将其存储在 C 中的字符串数组中

c++ - 具有某些成员的类的术语

java - 在哪里可以找到哪个库属于一个类?