Am 02.02.2013 21:20, schrieb Arup Rakshit:
> Why none of the block giving the expected output with the "enumerator"?

They do, you have wrong expectations. (You really should read the docs
and google for examples/tutorials/... to build the right expectations.)

(BTW, next time please *tell us* what your expected output would have
  been.)

> =======================================================================
> irb(main):017:0> a=[11,22,31,224,44].to_enum
> => #<Enumerator: [11, 22, 31, 224, 44]:each>
> irb(main):018:0> a.each{|x| x%2 == 0}
> => [11, 22, 31, 224, 44]
> irb(main):019:0> a.each{|x| x%4 == 0}
> => [11, 22, 31, 224, 44]
> irb(main):020:0> a.each{|x| x > 22 }
> => [11, 22, 31, 224, 44]

First, you do not need to_enum here, simply use Array#each.

Second, the blocks behave exactly as should be expected.

What you probably meant was something like

   1.9.3-p194 :001 > a = [11, 22, 31, 224, 44]
    => [11, 22, 31, 224, 44]
   1.9.3-p194 :002 > a.each {|item| puts item  if item % 2 == 0 }
   22
   224
   44
    => [11, 22, 31, 224, 44]

You did not 'do' anything with the logical expression inside the block.

What you probably misinterpreted as the output (the part after '=>')
is actually the value of the evaluated expresssion, which in this case
is the return value of the each method (-> the array itself, see docs).
Besides the output generated by puts statements etc., irb always
additionally outputs the value of the evaluated expression.

> irb(main):021:0> a.each{|x,y| x-y }
> TypeError: nil can't be coerced into Fixnum
>          from (irb):21:in `-'
>          from (irb):21:in `block in irb_binding'
>          from (irb):21:in `each'
>          from (irb):21:in `each'
>          from (irb):21
>          from C:/Ruby193/bin/irb:12:in `<main>'

This cannot work, because #each yields exactly one parameter (see docs).
y therefore always is nil and nil cannot be subtracted from x.


-- 
<https://github.com/stomar/>