Object#to_proc to be used as Hash#to_proc?

There is a cool example of using Hash#to_proc where you can map “keys” to the Hash as it is a function, and get the corresponding values.

Something like:

h = { a: 1, b: 2, c: 3, d: 4 }
[ :a, :c, :d, :b ].map(&h)
# => [ 1, 3, 4, 2 ]

Is it possible to get something similar for objects attributes? Like:

[:name, :lastname, :alias].map(&person)
#=> ["Jesús", "Gómez", "jgomo3"]

implement Person#to_proc to return a new Proc where the instance send its self the symbol where the symbol is a reader/accessor of an instance attribute:

class TestMe
  attr_reader :to_proc, :test_me
 
  def initialize(test_me_value)
      @test_me = test_me_value
      @to_proc = Proc.new {|sym| send(sym)}
  end
end

t = [:test_me]
t0 = TestMe.new "hello from procified"

p t.map(&t0)
1 Like