需要在Ruby和block中使用一个方法

man*_*rie 0 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

那种做法好吗?如何在块内使用其他方法?

这是我得到的错误:

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>'
Run Code Online (Sandbox Code Playgroud)

Jiř*_*šil 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
Run Code Online (Sandbox Code Playgroud)