Ruby: overrides puts method

I have a small program designed to run on IRB. It ultimately outputs what looks like an array, although technically it is not an array. (The class inherits from the array.) The problem is when I make an instance of this class, for example. example = Awesome.new (1,2,3) and I write "puts example", the default IRB behavior is to put each element of the example on its own line.

So instead

[1,2,3] 

(this is what I want) IRB issues this.

 1 2 3 

Is there any reasonable way to override the puts method for this special class? I tried this, but it did not work.

 def puts self.to_a end 

Any idea what I'm doing wrong?

Update: I tried this but did not succeed.

 def to_s return self end 

So, when Iโ€™m in IRB and I just type โ€œexampleโ€, I get the behavior that I am looking for (ie [1, 2, 3]. So I decided that I could just return myself, apparently that spoiled something, what I do not understand?

+4
source share
3 answers
 def puts(o) if o.is_a? Array super(o.to_s) else super(o) end end puts [1,2,3] # => [1, 2, 3] 

or just use p :

 p [1, 2, 3] # => [1, 2, 3] 
+3
source

You must override to_s and it will be processed automatically, just remember to return the string from to_s and it will work like a charm.


An example of a fragment ..

 class Obj def initialize(a,b) @val1 = a @val2 = b end def to_s "val1: #@val1\n" + "val2: #@val2\n" end end puts Obj.new(123,321); 

 val1: 123 val2: 321 
+5
source

You should probably implement the to_ary method for your class like Array. This method will be called by puts to get all the elements. I posted a snippet from one of my projects below

 require 'forwardable' class Path extend Forwardable def_delegators :@list, :<<, :count, :include?, :last, :each_with_index, :map def initialize(list = []) @list = list end def to_ary self.map.each_with_index{ |e, i| "#{e}, step: #{i}" } end end 
+1
source

All Articles