我是红宝石的新手。我一直在尝试鞋子,并且已经以这种方式多次看到函数调用:
somefunc "someparameter", "otherparameter" do
SomeFunctionContents
end
如何以相同的方式创建将此类函数作为最终参数的函数?我希望能够这样称呼它:
myFunction "myParameter" do
SomeStuffIWouldLikeToCallInMyFunction
end
我将如何实现?
到目前为止,我的尝试是:
def myfunc parameterone
doStuff
yield # In order to call the function passed after parameteone
doStuff
end
# AND LATER
myfunc "parameterone" def
myFuncStuff
end
这根本不起作用。
编辑尽管我的问题已解决,但为清楚起见,我将提供错误消息,因为这可能对犯相同错误的任何人有用。
syntax error, unexpected keyword_def, expecting end-of-input
我们称其为块。
def call_this_block
stuff = 'can be anything'
yield stuff
end
call_this_block { |x|
puts 'you can use brackets'
puts x
}
call_this_block do |x|
puts 'or you can use do/end blocks'
puts x
end
另外,Proc.new
不带参数的调用将模拟传递的块
def call_this_block
Proc.new.call(111)
end
call_this_block { |x| x ** 3 }
我认为您的错误在于对功能的误解def
。在ruby中,我们有方法和匿名函数,尽管它们就像近亲,但它们并不相同。
# def defines a method a attaches it to the current scope
def this_method
puts 'asdf'
end
# this method is "attached" so you can retrieve it at any time and even redefine it
method(:this_method)
=> #<Method: Object#this_method> # Object is the default scope where you are sitting
# call it
method(:this_method).call
this_method
# this one of the many available syntaxis to create anonym functions or methods
that_method = -> { puts 'is not attached' }
that_method.call
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句