From: sawadatsuyoshi@... Date: 2018-09-20T07:14:21+00:00 Subject: [ruby-core:89099] [Ruby trunk Feature#15143] Extend `Enumerable#to_h` Issue #15143 has been updated by sawa (Tsuyoshi Sawada). mame (Yusuke Endoh) wrote: > If the block returns an array whose length is > 2, how does it behave? > > ``` > %w(aa1 ab2 ba3 bb4).to_h {|s| s.chars } > #=> { "a" => { "a" => "1", > "b" => "2" }, > "b" => { "a" => "3", > "b" => "4" } } > ``` > > I expect very useful trie generator :-) My original proposal is to follow the behaviour of the current `map.{...}.to_h`, which means to raise `ArgumentError: wrong array length at 0 (expected 2, was 3)`. However, mame's proposal to extend the feature also sounds interesting and good. Though, after having Matz' acceptance of this proposal, I am not sure whether we can still get another approval on top of it from him assuming mame's extension, or whether the extension should be another issue. ---------------------------------------- Feature #15143: Extend `Enumerable#to_h` https://bugs.ruby-lang.org/issues/15143#change-74119 * Author: sawa (Tsuyoshi Sawada) * Status: Open * Priority: Normal * Assignee: nobu (Nobuyoshi Nakada) * Target version: ---------------------------------------- Often, we call `Array#to_h` to the result of `Enumerable#map`: ```ruby (1..5).map{|x| [x, x ** 2]}.to_h #=> {1=>1, 2=>4, 3=>9, 4=>16, 5=>25} ``` I am thinking of a feature to do this in a single method call. Currently, `Enumerable#to_h` does not accept a block. I propose that, when `Enumerable#to_h` is called with a block (that has a subarray representing a key-value pair), return a hash that would be returned by applying the block to `map`, and `to_h` to the result: ```ruby (1..5).to_h{|x| [x, x ** 2]} #=> {1=>1, 2=>4, 3=>9, 4=>16, 5=>25} ``` Ideally, I request this to be done internally to Ruby without creating an intermediate parent array. -- https://bugs.ruby-lang.org/ Unsubscribe: