0

Ruby 1.9.2 コード:

def append_string_to_text(string_to_append)
  string_to_alter = 'starting_bit'
  p "OUTSIDE BLOCK: string_to_alter.object_id is #{string_to_alter.object_id}"
  Proc.new do
    p "****** START OF BLOCK: string_to_alter.object_id is #{string_to_alter.object_id}"
    p "defined?(new_string_created_in_block) is #{defined?(new_string_created_in_block) == true}"
    unless defined?(new_string_created_in_block)
      p "new_string_created_in_block is undefined. lets define it."
      new_string_created_in_block = 'test'
    end
    p "new_string_created_in_block.object_id is #{new_string_created_in_block.object_id}"
    string_to_alter = string_to_alter + string_to_append
    p "END OF BLOCK: string_to_alter.object_id is #{string_to_alter.object_id}"
    string_to_alter
  end
end

proc = append_string_to_text('_text_at_the_end')
p proc.call
p proc.call

出力:

"OUTSIDE BLOCK: string_to_alter.object_id is 70283335840820"
"****** START OF BLOCK: string_to_alter.object_id is 70283335840820"
"defined?(new_string_created_in_block) is false"
"new_string_created_in_block is undefined. lets define it."
"new_string_created_in_block.object_id is 70283335840520"
"END OF BLOCK: string_to_alter.object_id is 70283335840440"
"starting_bit_text_at_the_end"
"****** START OF BLOCK: string_to_alter.object_id is 70283335840440"
"defined?(new_string_created_in_block) is false"
"new_string_created_in_block is undefined. lets define it."
"new_string_created_in_block.object_id is 70283335840180"
"END OF BLOCK: string_to_alter.object_id is 70283335840100"
"starting_bit_text_at_the_end_text_at_the_end"

ブロックが最初に実行されるとき、ブロックはクロージャーであるため、string_to_alter変数は最初にメソッドの開始時に作成されたオブジェクトを指します。append_string_to_textブロックは新しい変数を作成し、次に、外部変数をシャドウnew_string_created_in_blockする新しいブロック ローカル変数を作成します。string_to_alterstring_to_alter

ブロックが 2 回目に実行されると、string_to_alter変数は最初にブロックが最初に実行されたときに作成されたオブジェクトを指します。

この 2 回目の実行中にnew_string_created_in_blockが定義されていないのはなぜですか? 最初の実行時に割り当てられ、string_to_alter変数の割り当ては最初の実行から永続化されるのに、なぜnew_string_created_in_block永続化されないのでしょうか?

4

1 に答える 1