首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Ruby:打印和整理数组的方法

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

Stack Overflow用户
提问于 2013-04-03 18:09:27
回答 1查看 80.2K关注 0票数 29

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

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

代码语言:javascript
复制
current_humans = [.....]
current_humans.each do |characteristic|
  puts characteristic
end

然而,如果我有这个:

代码语言:javascript
复制
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

它不起作用。

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

代码语言:javascript
复制
puts Human.current_humans.inspect

但是我想学习其他的选择!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-03 18:14:21

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

代码语言:javascript
复制
humans = %w( foo bar baz )

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

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

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

也有pp (漂亮的打印),但您需要首先需要它。

代码语言:javascript
复制
require 'pp'

pp %w( foo bar baz )

pp可以更好地处理复杂对象。

顺便说一句,不要使用显式返回

代码语言:javascript
复制
def self.print  
  return @@current_humans.to_s    
end

应该是

代码语言:javascript
复制
def self.print  
  @@current_humans.to_s    
end

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

票数 54
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15784503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档