[英]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
. 当我调用
my_calling_method
来调用my_function
,我将args1
设为nil而不是def do_this return 2*3 end
。
Am I doing anything wrong? 我做错什么了吗? Can we pass method as an argument in Ruby?
我们可以在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. 好了,我现在尝试根据自己的需求实现Proc,但是我很难将其传递给调用方法。
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. 我使用的参考资料像我一样将Proc作为参数传递给该方法,但是我遇到错误,因为没有通过my_calling_method传递任何参数,零参数传递给了my_function。
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? 当您在IRB中运行该代码时,得到
nil
,对吗? 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
. 您将从方法定义中获取
nil
,因此nil
是传递给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
实际上,这就是您使用
.each
方法(或多或少) .each
array.each {|ele| foo}
I recommend reading up on Ruby's block, Procs, and Lambdas for passing methods in as arguments. 我建议阅读Ruby的代码块,Procs和Lambda,以将方法作为参数传递。
Nothing wrong. 没有什么不对。 A method definition returns
nil
. 方法定义返回
nil
。 The value of def do_this; return 2*3 end
def do_this; return 2*3 end
的值def do_this; return 2*3 end
def do_this; return 2*3 end
is nil
. def do_this; return 2*3 end
为nil
。 That is what you get. 那就是你得到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.