Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this ruby function return anything?

Tags:

ruby

I am working with legacy ruby code and I don't understand how this works. The fnction is:

    def determine_caller(host)
      if host["name"] =~ /special/
        method(:call_special)
      else
        method(:call_normal)
      end
    end

later on the method is called:

caller = determine_caller(host_name)

The program eventually then uses caller as a variable as it runs a method in another class. call_special and call_normal are methods later on in the program.

I believe this is defining a method to send to another method so it can later call the method as needed (either call_special or call_normal), but I don't understand how determin_caller returns anything. I thought the method keyword invoked the method itself, but that can't be right, at least how I understand the program I am looking at.

like image 653
WildBill Avatar asked Feb 28 '26 00:02

WildBill


2 Answers

The simple answer, without going into ruby object model or anything, is that the last statement in a method is always returned. So if the callers name is special than return what ever value is returned when the method 'method' is called with those parameters

like image 75
Schylar Avatar answered Mar 02 '26 13:03

Schylar


The Object#method method returns a Method. It doesn't call anything. (If it did, method would be an incredibly awful name for what it did.)

BTW: method is not a keyword and determine_caller is not a function. They are both methods.

like image 40
Jörg W Mittag Avatar answered Mar 02 '26 14:03

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!