Ruby: method to print and neat an array
Asked Answered
A

1

35

I am not sure if this question is too silly but I haven't found a way to do it.

Usually to puts an array in a loop I do this

current_humans = [.....]
current_humans.each do |characteristic|
  puts characteristic
end

However if I have this:

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

It doesn't work.

Of course I can use something like this

puts Human.current_humans.inspect

but I want to learn other alternatives!

Annuity answered 3/4, 2013 at 10:9 Comment(0)
M
61

You can use the method p. Using p is actually equivalent of using puts + inspect on an object.

humans = %w( foo bar baz )

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

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

But keep in mind p is more a debugging tool, it should not be used for printing records in the normal workflow.

There is also pp (pretty print), but you need to require it first.

require 'pp'

pp %w( foo bar baz )

pp works better with complex objects.


As a side note, don't use explicit return

def self.print  
  return @@current_humans.to_s    
end

should be

def self.print  
  @@current_humans.to_s    
end

And use 2-chars indentation, not 4.

Malkamalkah answered 3/4, 2013 at 10:14 Comment(2)
Hi, I know this is old but I was just doing some Katas and came across this post. Why should p not be used (deeper explanation than the debugging one if possible please)? Also I used p a and puts a.inspect on an array called 'a' and only p a worked. Am I missing something?Coot
I know 2 character indentation is standard in a lot of the ruby world. As someone legally blind, I have to say 2 character indentation fails me badly. Very hard to see the indent levels.Teetotum

© 2022 - 2024 — McMap. All rights reserved.