Skip to content

Instantly share code, notes, and snippets.

@aruprakshit
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aruprakshit/82d4d58274b7cf1c0b7e to your computer and use it in GitHub Desktop.
Save aruprakshit/82d4d58274b7cf1c0b7e to your computer and use it in GitHub Desktop.
Playing with Enumerable#to_a

Enumerable#to_a says, that it can take arguments also. Lets try

(1..4).to_a(1,2)
#ArgumentError: wrong number of arguments (2 for 0)

Oops! Why then error ? Because Enumerable#to_a called actually Range#each which don't accept any arguments. Now look the below code :-

class Foo
 include Enumerable
 def each(a, b, c)
   yield c
   yield b
   yield a
 end
end

Foo.new.to_a(1, 2, 3)
# => [3, 2, 1]

Now, we can see that Enumerable#to_a takes argument, if the receiver's class implements the #each method to support it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment