Ruby:打印和整齐数组的方法
发布时间:2020-12-16 20:40:14 所属栏目:百科 来源:网络整理
导读:我不知道这个问题是否太傻,但我没有找到办法. 通常要把一个数组放在一个循环中,我做到这一点 current_humans = [.....]current_humans.each do |characteristic| puts characteristicend 但是如果我有这个: class Human attr_accessor:name,:country,:sex @
我不知道这个问题是否太傻,但我没有找到办法.
通常要把一个数组放在一个循环中,我做到这一点 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检查.
humans = %w( foo bar baz ) p humans # => ["foo","bar","baz"] puts humans.inspect # => ["foo","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-chars缩进,而不是4. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |