Frage

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!"}
War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top