Jeremy Smith
Jeremy Smith

Reputation: 15079

Why does ary.each dump out all of the contents of an object?

foo is an array of objects, bar is an attribute of that object.

(rdb:1) foo.bar.map{|v| bar.v }
["a", "b", "c", "d", "e", "f"]


(rdb:1) foo.bar.each{|v| p bar.v }
[massive outpouring of object attributes]

Upvotes: 3

Views: 97

Answers (3)

Andrew Grimm
Andrew Grimm

Reputation: 81558

I think it's possible to tell IRB not to display return values. That'd solve your problem without having to put ; nil at the end of each line.

Alternatively, you could modify the inspect method of the bars so that it's less verbose.

class Bar
  def inspect
    "tl;dr"
  end
end

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146123

#each will return its receiver, and then irb will decide to helpfully print it, since irb is a REPL.

You could just tack a .any? on the end of the expression:

(rdb:1) foo.bar.each{|v| p bar.v }.any?
# output from only the #p call
=> true

Upvotes: 1

Wayne Conrad
Wayne Conrad

Reputation: 108079

Because the result of each is defined to be the Enumerable object being iterated over.

If you want to use each in irb and not get swamped with output, then:

foo.bar.each{|v| p bar.v }; nil

Upvotes: 6

Related Questions