Project

General

Profile

Actions

Bug #2212

closed

Using a Lambda with Inappropriate Arity for Hash#default_proc=

Added by runpaint (Run Paint Run Run) over 14 years ago. Updated almost 13 years ago.

Status:
Closed
Target version:
-
ruby -v:
ruby 1.9.2dev (2009-10-14 trunk 25330) [i686-linux]
Backport:
[ruby-core:26087]

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:in yield' from (irb):13:in default'
from (irb):13
from /usr/local/bin/irb:12:in `'
=end

Actions #1

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

Actions #2

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

Actions #3

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

Actions #4

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 writes:

|Thank you. Could the same logic be applied to Hash.new?

Indeed. This new check should be implementation dependent, IMO.

						matz.

=end

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0