我编写代码来了解如何在块中使用方法:
def block_trial alfa, &block
puts alfa
block.call
end
block_trial "Trial" do ||
puts "Komodo"
another_method
end
def another_method
puts "another_method"
end
这种方法可以吗?如何在块内使用其他方法?
这是我得到的错误:
block.rb:9:in `block in <main>': undefined local variable or method `another_method' for main:Object (NameError)
from block.rb:4:in `call'
from block.rb:4:in `block_trial'
from block.rb:7:in `<main>'
答案 0 :(得分:6)
another_method
。您需要将其定义移到您调用它的方法/位置之上。
def block_trial alfa, &block
puts alfa
block.call
end
def another_method
puts "another_method"
end
block_trial "Trial" do
puts "Komodo"
another_method
end