Bug #2212
closedUsing a Lambda with Inappropriate Arity for Hash#default_proc=
Description
=begin
If the default_proc of a Hash is a lambda whose arity != 2, key lookups raise an ArgumentError. To understand this exception the user must know that the hash has a default proc, lambdas perform strict argument checking, and that the lambda is passed two arguments.
Instead, perhaps Hash#default_proc and Hash.new could raise a helpful error message if they're passed a lambda with an arity other than 2. This localises the exception to where the default_proc is set, as opposed to where an element is referenced, and better explains the problem.
h={}
=> {}
h.default_proc=->{ true }
=> #<Proc:0x9eaaea8@(irb):12 (lambda)>
h[:key]
ArgumentError: wrong number of arguments (2 for 0)
from (irb):13:inyield' from (irb):13:in
default'
from (irb):13
from /usr/local/bin/irb:12:in `'
=end
Updated by marcandre (Marc-Andre Lafortune) over 14 years ago
- Assignee set to matz (Yukihiro Matsumoto)
=begin
There are other cases where Ruby C code calls user code. In particular with the new respond_to_missing? Example:
class A
def respond_to_missing?(method, private)
true
end
#....
end
A.new.method(:foo) # ==> valid method
A.new.respond_to?(:foo) # ==> ArgumentError: wrong number of arguments (1 for 2)
from (irb):1:in `respond_to?'
Although it's difficult to make an error when defining <=>, #sort and Comparable can give strange errors too if <=> has arity 0.
=end
Updated by matz (Yukihiro Matsumoto) over 14 years ago
- Status changed from Open to Closed
- % Done changed from 0 to 100
=begin
This issue was solved with changeset r25455.
Run Paint, thank you for reporting this issue.
Your contribution to Ruby is greatly appreciated.
May Ruby be with you.
=end
Updated by runpaint (Run Paint Run Run) over 14 years ago
=begin
Thank you. Could the same logic be applied to Hash.new?
h = Hash.new &->(a){}
h[:key]
ArgumentError: wrong number of arguments (2 for 1)
from (irb):2:in yield' from (irb):2:in
default'
from (irb):2
from /usr/local/bin/irb:12:in `
=end
Updated by matz (Yukihiro Matsumoto) over 14 years ago
=begin
Hi,
In message "Re: [ruby-core:26281] [Bug #2212] Using a Lambda with Inappropriate Arity for Hash#default_proc="
on Sun, 25 Oct 2009 04:51:30 +0900, Run Paint Run Run redmine@ruby-lang.org writes:
|Thank you. Could the same logic be applied to Hash.new?
Indeed. This new check should be implementation dependent, IMO.
matz.
=end