N
N
nevro2017-02-25 19:52:46
ruby
nevro, 2017-02-25 19:52:46

If a block is a closure, then why can't you access a local variable from it?

In this case, I can't access the name variable from the wrapper function:

def closure
    name = "локальная"
    puts "перед блоком"
    yield(name)  # name = yield(name)
    puts "после блока"
    puts name
end

closure do |word|
    puts "Внутри блока."
    word = word + " добавка от блока"
    puts word
    puts "Выход из блока."
    #   word
end

Output:
before the block
Inside the block.
local addition from the block
Exit from the block.
after the block
local

In the name of the framing function, "local addition from the block" will remain only if some lines are replaced with comments, and they are commented out. But why is that? So the blocks are not full-fledged closures?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Demidenko, 2017-02-25
@nevro

This is from not knowing that the + method creates a new object.
This is how you want it to be

closure do |word|
    puts "Внутри блока."
    word.concat " добавка от блока"
    puts word
    puts "Выход из блока."
    #   word
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question