Bug #5406

inconsistent odd-length array rejection in Hash[*ary] vs Hash[ary]

Added by Suraj Kurapati over 3 years ago. Updated over 2 years ago.

[ruby-core:39945]
Status:Closed
Priority:Normal
Assignee:Nobuyoshi Nakada
ruby -v:ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux] Backport:

Description

Hello,

Hash[*ary] raises an error when given odd number of arguments:

Hash.
ArgumentError: odd number of arguments for Hash
from (irb):3:in []'
from (irb):3
from /usr/bin/irb:12:in
'

In contrast, Hash[ary] silently accepts odd-length arrays:

Hash.
{}
Hash.
{
1 => 2
}
Hash.
{
1 => 2,
3 => nil
}
Hash.
{
1 => 2
}

I think this behavior is inconsistent. Please either:

(1) change Hash[ary] to raise errors upon seeing odd-length arrays or

(2) change Hash[*ary] to not raise an error for odd number of arguments and instead accept the last odd argument as a key with value nil, just like this existing behavior:

Hash.
{
1 => 2,
3 => nil
}

Thanks for your consideration.


Related issues

Related to Ruby trunk - Bug #1385: Wonderful undocumented feature in Ruby 1.8.7 & 1.9 Closed 04/17/2009

Associated revisions

Revision 36391
Added by Nobuyoshi Nakada over 2 years ago

hash.c: raise on invalid input

  • hash.c (rb_hash_s_create): raise an exception, when input elements are not one or two elements arrays. [Bug #5406]

Revision 36391
Added by Nobuyoshi Nakada over 2 years ago

hash.c: raise on invalid input

  • hash.c (rb_hash_s_create): raise an exception, when input elements are not one or two elements arrays. [Bug #5406]

History

#1 Updated by Koichi Sasada almost 3 years ago

  • Category set to core
  • Status changed from Open to Assigned
  • Assignee set to Yukihiro Matsumoto

#2 Updated by Yukihiro Matsumoto over 2 years ago

  • Assignee changed from Yukihiro Matsumoto to Nobuyoshi Nakada

Hash should raise an exception, when invalid input comes.

Matz.

#3 Updated by Nobuyoshi Nakada over 2 years ago

  • Status changed from Assigned to Closed
  • % Done changed from 0 to 100

This issue was solved with changeset r36391.
Suraj, thank you for reporting this issue.
Your contribution to Ruby is greatly appreciated.
May Ruby be with you.


hash.c: raise on invalid input

  • hash.c (rb_hash_s_create): raise an exception, when input elements are not one or two elements arrays. [Bug #5406]

Also available in: Atom PDF