From: "Carlo E. Prelz" Date: 2013-01-22T04:49:54+09:00 Subject: Re: Enumerator usage Subject: Enumerator usage Date: Tue 22 Jan 13 04:20:57AM +0900 Quoting David Richards (lists@ruby-forum.com): > I don't understand the following: > > 3.times { |i| puts(i) } # ok > 3.times.class # Enumerator > n = 3.times > n.class # Enumerator > n { |i| puts(i) } # error!? > > To a new Ruby student this error seems 'conceptually wrong'. Ruby documentation is well-made. Make good use of it! If you type ri Integer#times you will read: --8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<-- ------------------------------------------------------------------------------ int.times {|i| block } -> self int.times -> an_enumerator ------------------------------------------------------------------------------ Iterates block int times, passing in values from zero to int - 1. If no block is given, an enumerator is returned instead. --8<----8<----8<----8<----8<----8<----8<----8<----8<----8<----8<-- In your first example you pass a block, so it returns self. In the second example, you do not provide a block, and an enumerator is returned. Note that if you type 3.times { |i| puts(i) }.class you will get Integer (self, in this case, is the integer 3). What is an enumerator, then (which is returned by the Integer#times methods when you do not provide a block)? Use the documentation: read with care what you obtain when you type ri Enumerator > There just seems to be something really 'wrong' about how Ruby treats > functions: > > def f2(i) > puts(i) > end > > f2.class # error!? With def you define a method of the current class (or a method of the Object class if you are not defining your own class). You do NOT define a variable. If you want a variable to contain the reference to your new method, you must type vrb=method(:f2) and vrb will be an instance of the Method class, containing a reference to your method. > I'm hoping that once I understand it better > it will start to look 'elegant' and 'beautiful', but right now it looks > kinda 'scary' and 'repugnant'. 'scary' and 'repugnant' are two concepts that express fear. Fear is the first enemy that has to be won on the path of growth... Ruby is just different from what you are used to. But it works. > > Help please! > > - Dave > > -- > Posted via http://www.ruby-forum.com/. > -- * Se la Strada e la sua Virtu' non fossero state messe da parte, * K * Carlo E. Prelz - fluido@fluido.as che bisogno ci sarebbe * di parlare tanto di amore e di rettitudine? (Chuang-Tzu)