T
tfdj
hi all!
i encountered a strange problem with eval. please see the following
test case:
require 'test/unit'
class TestContext
def eval_in_context( ruby_code )
instance_eval ruby_code
end
def toast
@toast
end
def toast=( val )
@toast = val
end
end
class TestMetaEval < Test::Unit::TestCase
def test_toast
tc = TestContext.new
tc.toast = 'yes'
assert_equal 'yes', tc.toast
assert_equal 'yes', tc.eval_in_context( "toast" )
# These two lines - using explicit self - work as expected:
assert_equal 'maybe', tc.eval_in_context( "self.toast = 'maybe'" )
assert_equal 'maybe', tc.toast
# What is happening here:
assert_equal 'no', tc.eval_in_context( "toast = 'no'" )
# Why does the next test fail?
# What did the previous line set? A local variable?
# tc.toast returns 'maybe' here instead of the expected 'no':
assert_equal 'no', tc.toast
end
end
why is the 'toast=(val)' method not visible in eval unless i
explicitly use "self.toast = ..."?
what is it i don't understand about ruby scoping? :/
any help really appreciated!
cheers,
daniel
i encountered a strange problem with eval. please see the following
test case:
require 'test/unit'
class TestContext
def eval_in_context( ruby_code )
instance_eval ruby_code
end
def toast
@toast
end
def toast=( val )
@toast = val
end
end
class TestMetaEval < Test::Unit::TestCase
def test_toast
tc = TestContext.new
tc.toast = 'yes'
assert_equal 'yes', tc.toast
assert_equal 'yes', tc.eval_in_context( "toast" )
# These two lines - using explicit self - work as expected:
assert_equal 'maybe', tc.eval_in_context( "self.toast = 'maybe'" )
assert_equal 'maybe', tc.toast
# What is happening here:
assert_equal 'no', tc.eval_in_context( "toast = 'no'" )
# Why does the next test fail?
# What did the previous line set? A local variable?
# tc.toast returns 'maybe' here instead of the expected 'no':
assert_equal 'no', tc.toast
end
end
why is the 'toast=(val)' method not visible in eval unless i
explicitly use "self.toast = ..."?
what is it i don't understand about ruby scoping? :/
any help really appreciated!
cheers,
daniel