Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing methods in a lambda and sending to an object

Is is possible to call functions on (send messages to) an object if the functions are stored in a variable as a lambda?

Say I have an array like %w(a b c)

I can then chain methods like:

%w(a b c).reverse.map(&:upcase) # => ["C", "B", "A"] 

Is it possible to extract the chained method calls to a variable and apply them to other array objects?

transform = -> { reverse.map(&:upcase) }

I've tried the following but have not had any luck:

Using JRuby 1.7.1

%w(a b c).send(transform)
TypeError: #<Proc:0x19a639d8@(irb):12 (lambda)> is not a string

And

%w(a b c).send(&transform)
ArgumentError: wrong number of arguments (0 for 1)

Using Ruby 1.9.3

%w(a b c).send(transform)
TypeError: #<Proc:0x007fa0721f0dc8@(irb):1 (lambda)> is not a symbol

And

%w(a b c).send(&transform)
ArgumentError: no method name given
like image 533
Peter Brown Avatar asked Feb 19 '23 05:02

Peter Brown


1 Answers

I see at least two approaches:

1) You seem to like to write lambdas with an implicit receiver (I wouldn't recommend it, self obviously changes), you have instance_exec for that:

transform = -> { reverse.map(&:upcase) }
["a", "b", "c"].instance_exec(&transform)
#=> ["C", "B", "A"]

2) Write a custom extension, for example Object#apply:

class Object
  def apply(block, *args)
    block.call(self, *args)
  end
end

transform = -> strings { strings.reverse.map(&:upcase) }
["a", "b", "c"].apply(transform)
#=> ["C", "B", "A"]
like image 82
tokland Avatar answered Mar 03 '23 08:03

tokland