ruby - Misunderstanding about Object#tap -


here simple test code:

def test_function   0.tap |v|     v += 10   end end  p test_function 

why 0 here ? waiting 10.

update:

class testclass     def initialize         @v = 0     end      def inc          @v = @v + 1     end end  def test_function     0.tap |v|         v += 10     end end  def test_function_2     testclass.new.tap { |obj|         obj.inc     } end  p test_function p test_function_2 

0

testclass:0x29244f0 @v=1

the reason original object not changed += operator. happens create reference in block, change reference point other object, larger 10 , return. value of 0 stays same.

and thing -- want happen. += operator not change object operates on. returns another different object , assigns reference it. like:

  v = 0   v = v + 10 

you wouldn't expect 0 == 10 true after this, right?


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -