문제

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!"}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top