简体   繁体   中英

In Ruby, how to tell two methods or two functions are the same?

For example, to check whether

CGI::parse == CGI.parse

(after doing require "cgi" ), how can it be done?

CGI.parse is not valid code, since you are calling the method (without arguments, and the method requires one).

However, in ruby, (almost) everything is an object -- which includes methods! (A method is an instance of the class: Method .)

You can access the CGI::parse method via: CGI.method(:parse) .

Then, to check that two methods are equal, you can use the == method on the Method class :

CGI.method(:parse) == CGI.method(:parse) #=> true

From the ruby documentation:

Two method objects are equal if they are bound to the same object and refer to the same method definition and their owners are the same class or module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM