- Short Ruby Newsletter
- Posts
- Ways to call a method in Ruby
Ways to call a method in Ruby
#code #summary #method #calls #ruby
This is a code summary for https://www.notonlycode.org/12-ways-to-call-a-method-in-ruby/


![# Part 3️⃣/4: Other ways to call a method # with __send__ service.__send__(:post, "Extra #1!") # Using [] shorthand syntax for call service.method(:post)["Extra #2!"] # With lambda service.tap(&->(object) { object.post("Extra #3!")}) # or post_lambda=->(service) { service.post("Extra #4!")} service.tap(&post_lambda) # With proc service.tap(&(Proc.new { _1.post("Extra #5!")})) # or post_proc=Proc.new { _1.post("Extra #6!")} service.tap(&post_proc) # It works with `then` too if you want to get the result also # `tap` will discard the result result=service.then { _1.post("Extra #7!") }](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/69b3724c-0ab4-409b-bc0e-9209b35945d4/d9a742d6-a113-4ebe-96ad-cf5b029963f2_1428x1020.png?t=1726892716)
![# Part 4️⃣/4: using bind and binding method=TweetService.instance_method(:post) method.bind(service).call("Extra #8!") # with bind, you can change the context where this executes class ClientOauthV2 def send(message) = puts "[OauthV2] #{message}" end class TweetServiceV2 < TweetService def initialize(client = ClientOauthV2.new) = super end new_service=TweetServiceV2.new method.bind(new_service).call("Extra #9!") # You can also get binding and then eval in that context class TweetServiceV2 < TweetService def get_binding=binding end context=new_service.get_binding context.eval("post('Extra #10!')") # or eval("post('Extra #11!')", context)](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/c33ca3fc-40cb-4252-8562-f32d9675e050/7b968dcd-3a6b-4eaf-b1c1-c19abfc48957_1432x1132.png?t=1726892717)
The source code if you want to play with this is here.
Reply