Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: overriding the puts method

Tags:

ruby

irb

I've got a small program meant to be run in IRB. It ultimately outputs something that looks like an array, though technically isn't an array. (The class inherits from array.) The problem is, when I do an instance of this class, e.g. example = Awesome.new(1,2,3), and I write "puts example", IRB's default behavior is to put each element of example onto it's own line.

So instead of

[1,2,3]

(which is what I want), IRB pops out this.

1
2
3 

Is there a smart way to override the puts method for this special class? I tried this, but it didn't work.

def puts
  self.to_a
end

Any idea what I'm doing wrong?

Update: So I tried this, but no success.

def to_s
  return self
end

So when I'm in IRB and I just type "example", I get the behavior I'm looking for (i.e. [1, 2, 3]. So I figured I could just to return self, but I'm still messing up something, apparently. What am I not understanding?

like image 322
Ben Downey Avatar asked Jul 13 '12 03:07

Ben Downey


1 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] 
like image 145
ted Avatar answered Sep 23 '22 02:09

ted