gpt4 book ai didi

ruby - 将函数作为最终参数传递

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:30 25 4
gpt4 key购买 nike

我是 ruby 新手。我一直在试鞋,并且多次看到这种方式的函数调用:

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

最佳答案

我们称之为 block 。

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 将模拟传递的 block

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

关于ruby - 将函数作为最终参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27493464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com