Project

General

Profile

Feature #11653

Add to_proc on Hash

Added by danielpclark (Daniel P. Clark) over 4 years ago. Updated almost 4 years ago.

Status:
Closed
Priority:
Normal
Target version:
-
[ruby-core:71327]

Description

Procs can be called the same way a hash is with []. But a Hash is not mappable as a Proc.

    my_hash = ->key{{
      a: 1, b: 2, c: 3, d: 4, e: 5, f: 6
    }[key]}

    my_hash[:a]
    # => 1

    [:e, :a, :b, :f, :c, :d].map(&my_hash) # hash is now mappable
    # => [5, 1, 2, 6, 3, 4]

This seems so straight forward I believe it should be part of the language itself with the .to_proc method call.

Updated by duerst (Martin Dürst) over 4 years ago

  • Assignee set to matz (Yukihiro Matsumoto)

I think this is an excellent idea. I hope this can make it into Ruby 2.3.

Updated by nobu (Nobuyoshi Nakada) over 4 years ago

  • Description updated (diff)

You can write it as:

[:e, :a, :b, :f, :c, :d].map(&my_hash.method(:[]))

Updated by matz (Yukihiro Matsumoto) over 4 years ago

  • Assignee changed from matz (Yukihiro Matsumoto) to nobu (Nobuyoshi Nakada)

Accepted.

Matz.

#5

Updated by nobu (Nobuyoshi Nakada) over 4 years ago

  • Status changed from Open to Closed

Applied in changeset r52520.


hash.c: to_proc

  • hash.c (rb_hash_to_proc): new method Hash#to_proc. [Feature #11653]

Updated by jwmittag (Jörg W Mittag) almost 4 years ago

Daniel P. Clark wrote:

Procs can be called the same way a hash is with []. But a Hash is not mappable as a Proc.

    my_hash = ->key{{
      a: 1, b: 2, c: 3, d: 4, e: 5, f: 6
    }[key]}

    my_hash[:a]
    # => 1

    [:e, :a, :b, :f, :c, :d].map(&my_hash) # hash is now mappable
    # => [5, 1, 2, 6, 3, 4]

This seems so straight forward I believe it should be part of the language itself with the .to_proc method call.

This is basically a subset of what I proposed a year ago in #11262. I additionally proposed that Hash also implement call. IMO, it doesn't make much sense to have one without the other: both methods basically say "hey, I'm kinda like a function", and a Hash is basically just a function from keys to elements. I proposed the same thing for Array and Set, which are essentially also just functions from indices to elements (Array) or elements to booleans (Set). However, so far, there has been no interest in that ticket.

Updated by duerst (Martin Dürst) almost 4 years ago

Jörg W Mittag wrote:

This is basically a subset of what I proposed a year ago in #11262.

Commenting on a closed issue won't help much to move an open issue forward. One thing that might help is to split Feature #11262 into smaller issues that can be discussed more easily.

A Hash is basically just a function from keys to elements.

Yes. The most direct case is Hash.new { |h, k| my_function(k) }. :-)

Also available in: Atom PDF