require!

R

Ross Bamford

I always thought it looked for to_ary... now someone says it looks
first for to_ary, then to_a.

And I had no idea that it would work with just #each defined.

When I kicked this thread off, I'd just done some quick tests that
suggested it worked like above, and on anything with each, and I guessed
that (since Enumerable defines to_a, and everything is in terms of each)
that it must work that way.
I'm still pretty sure it does to_ary followed by to_a, but as others
showed me, it doesn't actually work with just 'each'.

class Clazz
def each
yield 1
yield 2
yield 3
end
end

c = Clazz.new
c = [*c]
p c => [#<Clazz:0xb7f7ccdc>]

That's I think coming from the default to_a, and with the 1.9 snapshot I
have it gives a TypeError ('Cannot convert Clazz into Array' - the default
to_a is gone). It does _seem_ to work on anything with each if you include
Enumerable, but that's because Enumerable defines everything (including
to_a) in terms of 'each'. If you add 'include Enumerable' to the class
definition above, you get [1,2,3] as expected.
 
J

James Edward Gray II

I always thought it looked for to_ary... now someone says it looks
first for to_ary, then to_a.

And I had no idea that it would work with just #each defined.

It doesn't:
NoMethodError: undefined method `to_a' for #<NoArr:0x30d980>
from (irb):14

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top