0

I'm trying to pass min and then later max to a method, but it doesn't seem to work.

def worker(x)
  [3,4].x
end

worker(min)
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • 1
    @muistooshort I disagree with the decision to close this. The other question is explicitly about calling by name, this one is asking about passing methods as arguments and has potentially valid answers involving lambdas, yield, or block passing. – pjs Jun 28 '14 at 18:20
  • @pjs I'm sure there would be duplicates for that expanded scope too. Of course, the question isn't clear enough to warrant that expansion but you're welcome to try to convince enough people otherwise. – mu is too short Jun 28 '14 at 18:34
  • If you really mean "pass a method" you have to *pack* method into an object. Methods (as blocks - not lambdas and procs) are one of the few exception of "everything is an object" rule. `max = Array.instance_method :max` - now `max` is the object, without `self`. `arr = [1,2,3]; min.bind(arr).call` - you make `arr` aware of this one particular method, and you call it. You can read more about `UnboundMethod` class here: http://www.ruby-doc.org/core-1.9.3/UnboundMethod.html This: http://www.ruby-doc.org/core-1.9.3/Method.html might be useful too. – Darek Nędza Jun 28 '14 at 18:39
  • Can't format this for readability since answers are closed, but: `def worker(ary, &block); block.call ary; end`. Then `worker([3,4]) {|x| x.min} # => 3` and `worker([10, 20, 5]) {|x| x.max} # => 20`. In other words, neither the array to be operated on nor the operation are hard-wired. – pjs Jun 28 '14 at 22:25

1 Answers1

1

Do you want call methods by name? Then, use Object#send.

def worker(x)
  [3,4].send(x)
end

worker(:min)
# => 3
worker(:max)
# => 4
falsetru
  • 357,413
  • 63
  • 732
  • 636