Home>

I'm sorry for lack of study.
I couldn't understand it with my head. . .

What you do n’t understand

I don't know why this Proc instance holds a value and can increment each time I call

def get_counter (start)
  Proc.new {| n | start + = n}
end
count_up = get_counter (1)
count_up.call (1) # =>2
count_up.call (1) # =>3
count_up.call (1) # =>4
Thinking

(1)

count_up = get_counter (1)
# At this time, Proc instance assigned to variable count_up
Proc.new {| n | 1 + = n}
# 1 = 1 + n isn't strange ...?
# I thought that it would be preserved that it was executed in Proc, I tried it
count_up = Proc.new {| n | 1 + n}
count_up.call (1) # =>2
count_up.call (1) # =>2

(2) If this is the case, I understand the meaning ...

start = 1
count_up = Proc.new {| n | start + = n}
count_up.call (1) # =>2
count_up.call (1) # =>3
  • Answer # 1

      

    (1)

    "Constant1" is different from "Variable whose initial value is1".

      

    (2)

    Yes. It is the same mechanism.

Related articles