From: Oliver Peng Date: 2008-03-08T01:28:24+09:00 Subject: Re: the value in ensure block is not returned Robert Klemme wrote: > 2008/3/6, Oliver Peng : >> > Why should it? If you think about it you will see that it's actually >> > Yes, no problem here. >> >> irb(main):012:0> test >> => 2 >> >> It looks that the result value has been saved to a temp place before >> running ensure block. Is that correct? > > The return value is determined the very moment the block ends, which > means that the *reference* is saved (as always in Ruby). But since > you used Fixnums and simply reassigned to b ("b += 3") this won't be > visible. But > > irb(main):001:0> def t > irb(main):002:1> s="foo" > irb(main):003:1> ensure > irb(main):004:1* s.replace "see?" > irb(main):005:1> end > => nil > irb(main):006:0> t > => "see?" > irb(main):007:0> > > In other words, of course you can change the object before it is > returned. > >> irb(main):021:1> end >> => nil >> irb(main):023:0> test1 >> => 3 >> irb(main):024:0> @@value >> => 8 > > Same story: you reassigned. > > Cheers > > robert Ok I see. If I want to change the return value in ensure block, I need to change the object itself in the last line before ensure, not just reassign the varialbe. I also write another test code which can demonstrate clearly: irb(main):003:0> class A irb(main):004:1> attr_accessor :value irb(main):005:1> end => nil irb(main):006:0> def test irb(main):007:1> begin irb(main):008:2* a = A.new irb(main):009:2> a.value = 1 irb(main):010:2> a irb(main):011:2> ensure irb(main):012:2* a.value = 2 irb(main):013:2> end irb(main):014:1> end => nil irb(main):015:0> test => # I also did a test to try to do return in ensure block and it has higher priority. Here is my test code: irb(main):022:0> def test irb(main):023:1> begin irb(main):024:2* a = 1 irb(main):025:2> a irb(main):026:2> ensure irb(main):027:2* return 2 irb(main):028:2> end irb(main):029:1> end => nil irb(main):030:0> test => 2 Finally I think the best way is to avoid returning value in ensure block and always put the return value in the last line of function or use return directly. Thanks for your replay. -- Posted via http://www.ruby-forum.com/.