What does send() do in Ruby?

后端 未结 6 1025
野性不改
野性不改 2020-11-28 01:49

Can someone please tell me what

send(\"#{Model.find...}\")

is and does?

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 02:11

    What does send do?

    send is another way of calling a method.

    This is best illustrated by example:

    o = Object.new
    o.send(:to_s) # => "#"
    # is equivalent to:
    o.to_s # => "#"
    

    Send lives in the Object class.

    What is the benefit of ths?

    The benefit of this approach is that you can pass in the method you want to call as a parameter. Here is a simple example:

    def dynamically_call_a_method(name)
        o = Object.new
        o.send name 
    end
    dynamically_call_a_method(:to_s) # => "#"
    

    You can pass in the method you want to be called. In this case we passed in :to_s. This can be very handy when doing ruby metaprogramming, because this allows us to call different methods according to our different requirements.

提交回复
热议问题