Backport #9270

Array#to_h should not ignore badly formed elements

Added by Marc-Andre Lafortune 4 months ago. Updated 4 months ago.

[ruby-core:59235]
Status:Closed
Priority:Urgent
Assignee:Yui NARUSE

Description

The upcoming Array#toh feature currently ignores elements that are not 2-elements arrays. Array#toh could instead raise an error on those elements. I argued otherwise before, but maybe that would be safer.

One reason I think I was wrong is that current form could encourage code like:

enum.map{|x| [x.foo, x.bar] if x.baz? }.to_h

using the fact that any nil will be ignored. I'm not sure that it's a good idea.

It would probably be safer to raise an Exception for elements that are not a key-value pair. It also satisfies fail-early principle.

@sawa agrees with this.
@matz agrees with the change.

Since this feature has not already been released in an official version, changing this behavior now would not cause any incompatibility and there should be no risk of regression. Changing this feature after the official 2.1 release would be more problematic as it could cause incompatibilities.

Yui, could you please confirm that there is no problem on your end for me to commit the following patch: https://github.com/marcandre/ruby/compare/to_h_raise


Related issues

Related to ruby-trunk - Feature #9239: Array#to_h ignores flat arrays Rejected 12/11/2013

Associated revisions

Revision 44361
Added by Yui NARUSE 4 months ago

merge revision(s) 44354: [Backport #9270]

* array.c: Have to_h raise on elements that are not key-value pairs
  [#9239]

* enum.c: ditto

History

#1 Updated by Yui NARUSE 4 months ago

OK, could you commit it?
I'll backport it to ruby21 branch.

#2 Updated by Marc-Andre Lafortune 4 months ago

  • Tracker changed from Feature to Backport
  • Project changed from ruby-trunk to Backport21
  • Category deleted (core)
  • Target version deleted (2.1.0)

Great, thanks.

Committed as r44354

#3 Updated by Yui NARUSE 4 months ago

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

This issue was solved with changeset r44361.
Marc-Andre, thank you for reporting this issue.
Your contribution to Ruby is greatly appreciated.
May Ruby be with you.


merge revision(s) 44354: [Backport #9270]

* array.c: Have to_h raise on elements that are not key-value pairs
  [#9239]

* enum.c: ditto

Also available in: Atom PDF