0

I need to run multiple methods from an array like the folowing example, first approach works but i'd rather let just run the methods without displaying the result. How to adapt the second approach so that i don't get the error below ?

def method1
  print 1
end

def method2
  print 2
end

[method1, method2].each(&p) #=>12 (works)

[method1, method2].each(&method(:run)) 
#=>12 `method': undefined method `run' for class `Object' (NameError)
4
  • Your methods print things. Why would you want to run them if you don't want the printing? Commented Jan 29, 2013 at 10:27
  • just run, the print inside is just to seee waht is happening Commented Jan 29, 2013 at 10:28
  • Yeah, so they are running, aren't they? Remove print and you're good, no? Commented Jan 29, 2013 at 10:30
  • you are missing teh point Sergio, i want to run the methods without using the p, thanks anyway, i got the answer allready Commented Jan 29, 2013 at 10:37

1 Answer 1

2

Because method1 invokes the method (rather than referring to it), your arrays actually contain the results of running the methods, not references to the methods themselves.

You probably want:

[:method1, :method2].each {|m| method(m).call}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.