简体   繁体   中英

How can I pass a method as an argument in Ruby?

I am passing a method as an argument to a called function:

def my_function(args1)
   puts args1
end

def my_calling_method
   self.my_function(def do_this 
             return 2*3
           end)
end

When I call my_calling_method which makes a call to my_function , I am getting args1 as nil instead of def do_this return 2*3 end .

Am I doing anything wrong? Can we pass method as an argument in Ruby?

Alright, I tried implemented a Proc for my requirement now but I am having a hard time to pass it to the calling method.

my_Proc = Proc.new do
    return 2*3
end

def my_calling_method
    self.my_function
end

def my_function my_Proc
   my_Proc.call
end

The reference material I used passes a Proc as an argument to the method like I do, but I am getting error, zero arguments passed to my_function as I am not passing any argument through my_calling_method.

Defining a new method will not return a value. (Much like writing down a phone number does not result in a conversation.)

irb:001>def something
irb:002>   # code here
irb:003>end
=> nil

When you run that in IRB, you get nil , right? So, if you define that method as part of a method call:

some_method( def something; stuff; end )

You are getting back nil from the method definition and hence nil is what gets passed into some_method .

Without knowing exactly what it is you are trying to accomplish, I will tell you that you can pass methods, or what are called "blocks", into your method call.

def my_function(&block)
  puts block.call
end

my_function {2*3}
#=> 6
my_function {t = Time.now; t + 8640}
#=> 2013-08-09 14:03:29 -0500
my_function do 
   name = "Charlie"
   name.downcase.reverse.capitalize
end
#=> Eilrahc

In fact, this is what you are doing (more or less) with the method .each

array.each {|ele| foo}

I recommend reading up on Ruby's block, Procs, and Lambdas for passing methods in as arguments.

Nothing wrong. A method definition returns nil . The value of def do_this; return 2*3 end def do_this; return 2*3 end is nil . That is what you get.

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