gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:27:39 26 4
gpt4 key购买 nike

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

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com