How do I reference a function in Ruby?

前端 未结 4 1593
旧巷少年郎
旧巷少年郎 2020-12-05 00:32

In python, it\'s fairly straightforward to reference a function:

>>> def foo():
...     print \"foo called\"
...     return 1
... 
>>> x =          


        
4条回答
  •  情书的邮戳
    2020-12-05 00:43

    The (main) difference between functions and methods as copied from https://stackoverflow.com/a/26620095/226255

    Functions are defined outside of classes, while methods are defined inside of and part of classes.

    Ruby does not have functions and your def foo ends up being a method for the Object class.

    If you insist on defining foo like you're doing above, you can extract its "functionality" by doing this:

    def foo(a,b)
     a+b
    end
    
    x = method(:foo).to_proc
    x.call(1,2)
    => 3
    

    Explanation:

    > method(:foo) # this is Object.method(:foo), returns a Method object bound to 
    # object of type 'Class(Object)'
    => #
    
    method(:foo).to_proc
    # a Proc that can be called without the original object the method was bound to
    => #
    

    Important note:

    to_proc "copies" the method's object's associated instance variables if any. Consider this:

    class Person
      def initialize(name)
        @name = name
      end
    
      def greet
        puts "hello #{@name}"
      end
    end
    
    greet = Person.new('Abdo').method(:greet) 
    # note that Person.method(:greet) returns an UnboundMethod and cannot be called 
    # unless you bind it to an object
    
    > greet.call
    hello Abdo
    => nil
    

    Conceptually, if you want a "function" that would work on a certain type of objects, it should be a method and you should organize your code as such. If you only need your "function" in a certain context and wish to pass it around, use lambdas:

    greet = lambda { |person| "hello #{person}" }
    yell_at = lambda { |person| "HELLO #{person.upcase}" }
    
    def do_to_person(person, m)
      m.call(person)
    end
    
    do_to_person('Abdo', greet)
    

提交回复
热议问题