我是红宝石的新手。 我一直在试鞋,并且已经多次看到过这种方式的函数调用:
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
答案 0 :(得分:2)
我们称之为阻止。
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
的误解。在红宝石中,我们有方法和匿名函数,虽然它们像近亲,但它们并不相同。
# 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
答案 1 :(得分:2)
正如@nicooga所说,他们在Ruby中被称为块。你可以使用“block_given?”检测一个块在被调用时是否被传递给函数然后屈服。
def sayHello
puts "hello"
if block_given?
yield
end
puts "hello again"
end
# pass a block to it
sayHello do
puts "(exectute some task)"
end
# don't pass a block to it
sayHello