需要在Ruby&block里面使用一个方法

Need to use a method inside Ruby &block

我编写了代码来了解如何在块内使用方法:

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>'

another_method 直到你调用它之后才被定义。您需要将其定义移到您调用它的 method/place 上方。

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