Ruby:打印和整理数组的方法
我不确定这个问题是否太傻,但我还没有找到解决的办法 通常,为了将数组放入循环中,我会这样做Ruby:打印和整理数组的方法,ruby,arrays,class,puts,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 = [.....]
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
但我想学习其他的选择 您可以使用方法
p
。使用p
实际上相当于在对象上使用放置+检查
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
(如果可能的话,请提供比调试更深入的解释)?我还使用了pa
和将a.inspect
放在一个名为“a”的数组上,只有pa
起作用。我错过什么了吗?
def self.print
@@current_humans.to_s
end