Block.arity when using each_with_index

Hi,

I have a class with a custom iterator (each) that uses block.arity to
determine how many arguments to use on the yield. It works well but
when the caller invokes the iterator via each_with_index, the value
of block.arity is -1 which wreaks havoc. Does anyone know how to get the
correct value of block.arity in this situation?\

ruby -v
ruby 1.9.3p0 (2011-10-30) [x86_64-linux]

Here is the sample code:

#!/usr/bin/ruby -w

test block.arity value with each_with_index

class A
include Enumerable

def each( p, &b )
puts “arity = #{b.arity}”
yield ‘hello’, ‘world’
end
end

a = A.new
a.each( 0 ) { |x, y| puts “x = #{x}, y = #{y}” }
a.each_with_index( 0 ) { |(x, y), i| puts “x = #{x}, y = #{y}” }

Here is the output:

arity = 2
x = hello, y = world
arity = -1
x = hello, y = world

Why do you need to check the arity at all? If your method behaves
differently depending on the number of block arguments, it’s a clear
sign you need two different methods.

2011/11/23, Bug F. [email protected]:

def each( p, &b )
Here is the output:

arity = 2
x = hello, y = world
arity = -1
x = hello, y = world


Posted via http://www.ruby-forum.com/.


Wysłane z mojego urządzenia przenośnego

– Matma R.

-----Messaggio originale-----
Da: Bug F. [mailto:[email protected]]
Inviato: mercoled 23 novembre 2011 04:13
A: ruby-talk ML
Oggetto: block.arity when using each_with_index

Hi,

I have a class with a custom iterator (each) that uses block.arity to
determine how many arguments to use on the yield. It works well but when
the
caller invokes the iterator via each_with_index, the value of
block.arity is
-1 which wreaks havoc. Does anyone know how to get the correct value of
block.arity in this situation?\

ruby -v
ruby 1.9.3p0 (2011-10-30) [x86_64-linux]

Here is the sample code:

#!/usr/bin/ruby -w

test block.arity value with each_with_index

class A
include Enumerable

def each( p, &b )
puts “arity = #{b.arity}”
yield ‘hello’, ‘world’
end
end

a = A.new
a.each( 0 ) { |x, y| puts “x = #{x}, y = #{y}” } a.each_with_index( 0 )
{
|(x, y), i| puts “x = #{x}, y = #{y}” }

Here is the output:

arity = 2
x = hello, y = world
arity = -1
x = hello, y = world


Posted via http://www.ruby-forum.com/.


Caselle da 1GB, trasmetti allegati fino a 3GB e in piu’ IMAP, POP3 e
SMTP autenticato? GRATIS solo con Email.it http://www.email.it/f

Sponsor:
ING DIRECT Conto Arancio. 4,20% per 12 mesi, zero spese, aprilo in due
minuti!
Clicca qui: http://adv.email.it/cgi-bin/foclick.cgi?mid921&d)-12