manorie
manorie

Reputation: 69

Need to use a method inside Ruby &block

I wrote code to understand how I can use a method inside a 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

Is that kind of approach OK? How can I use another method inside the block?

This is the error I'm getting:

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

Upvotes: 0

Views: 50

Answers (1)

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14402

another_method is not defined until after you call it. You need to move its definition above the method/place you call it in.

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

Upvotes: 6

Related Questions