ruby - Pass a function into another function and call it -


Functions in Ruby are not first-class objects, but I want to be able to pass a reference to a function in another function. And it should be executed. How can this be done?

Example:

  def run_a_function_twice (my_function) # Call the function once. Call again #function and saydehello say "hi!" Finally run_A_function_ty (say_hello)  

I am reading the document, but I'm not sure that I should try Lambda, Processes or call (I only know the concept of call I can do it in two different ways:

You can do it in two different ways:

Ol>

  • Pass the name of the method (usually as a symbol, but a string will also work):

      send def run_a_method_twice (method_name) (metho D_name) Send (method_name) end run_a_method_twice (: Say_hello)  

    It depends on say_hello as if run_a_method_twice , same as Available in the scope if they are both examples in the same class, if say_hello was defined on another object, then you will do this some_obj.send (: say_hello) .

    You can provide logic in the method by giving them the send after the name of the method, e.g. jordan.send (: say_hello, "donny") .

  • Use a block:

      def yield_to_a_block_twice yield yield yield_to_a_block_twice {say_hello}  

    This syntax also works:

      def call_a_block_twice (and block) block.call block.call end  

    You may possibly produce < / Code> should be used (it is fast), but sometimes it is necessary to refer to the block by name (for example if there is another way you have to pass it, or it is within the second block ), In which it is a Named argument (i.e. def meth (arg1, arg2, and block_name) ) is required.

    Distinguishing between Block, Prok and Lambda are challenging for Ruby's newcomers, and a lot is written about them - just Google "Ruby Block Pro Lambda." Here's a great article to get started:


  • Comments

    Popular posts from this blog

    c# - SignalR: "Protocol error: Unknown transport." when navigating to hub -

    c# - WPF Expander overlay used in ItemsControl -

    android - how to get distance of 2 beacons and make a condtion base on that distance -