From: Stefano Crocco Date: 2013-02-03T05:34:08+09:00 Subject: Re: Why none of the block giving the expected output with the "enumerator"? On Sunday 03 February 2013 Arup Rakshit wrote > Why none of the block giving the expected output with the "enumerator"? > > ======================================================================= > irb(main):017:0> a=[11,22,31,224,44].to_enum > => # > 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] > 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 `
' > irb(main):022:0> a.each{|x,y| (x-y) } > TypeError: nil can't be coerced into Fixnum > from (irb):22:in `-' > from (irb):22:in `block in irb_binding' > from (irb):22:in `each' > from (irb):22:in `each' > from (irb):22 > from C:/Ruby193/bin/irb:12:in `
' > irb(main):023:0> > ====================================================================== > > -- > Posted via http://www.ruby-forum.com/. You create an enumerator from an array. When the enumerator's each method is called, it'll call the array's each method, which calls the block for every element and returns the array itself. In your first example, you execute the expression x%2==0 for each element, but you do nothing for the result. If you want to display the result, you'll need something like a.each{|x| puts(x%2==0)} If you want to select only those elements you'll want to use Enumerable#select rather than Enumerable#each: a1 = a.select{|x| x%2==0} I hope this helps Stefano