Reputation: 9043
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
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