megashigger
megashigger

Reputation: 9043

Using yield statement for blocks when you have multiple arguments

The error message I get when I run this code is "undefined local variable or method `john'". Am I not allowed to define a method with arguments if I have a yield statement?

def greet(name)
    puts "hello #{name}"
    yield
end

greet(john) {puts "Nice to meet you!"}

Upvotes: 0

Views: 229

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

You should call as :

greet('john') {puts "Nice to meet you!"}

Corrected code :-

def greet(name)
    puts "hello #{name}"
    yield
end

greet('john') {puts "Nice to meet you!"}
# >> hello john
# >> Nice to meet you!

If you write 'john' as john only, this will not be treated as string, rather Ruby will try to find it if any local variable or method having the same name exist. If not found, then the error will be thrown as you experienced.

Upvotes: 1

Related Questions