LoginSignup
2
2

More than 5 years have passed since last update.

Rubyのバージョンによるブロックローカル変数の挙動の違い

Posted at

一度ハマったのでメモ。
以下のテストスクリプトを、1.8 1.9 2.0 それぞれで実行してみる。

test_block.rb
puts "ruby version: #{RUBY_VERSION}"

a = 1
puts "before: #{a}"

# 外側にある変数と同名のブロックローカル変数に、値を代入
lambda{|a| a = "foo"}.call(nil)

puts "after : #{a}"
1.8の実行結果
ruby version: 1.8.7
before: 1
after : foo
1.9の実行結果
ruby version: 1.9.3
before: 1
after : 1
2.0の実行結果
ruby version: 2.0.0
before: 1
after : 1

ruby 1.8 だと、ブロックの外側の同名の変数に代入をした場合に、外側の変数も上書きされる。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2