ruby - How to replace 'nil' with a value using sub -


i trying substitute nil value using sub isn't happening. wrong.

a="" a.sub!(//,"replaced") puts #=> "replaced"  b=nil b.to_s.sub!(//,"replaced")  #tried => (b.to_s).sub!(//,"replaced") didnt work puts b #=> nil 

what missing?

to understand happening, let's follow code statement statement:

a=""                       # create new string object (the empty string), assign a.sub!(//,"replaced")      # sub! changes string object puts #=> "replaced"      # changed string printed  b=nil                      # assign nil b b.to_s.sub!(//,"replaced") # 2 steps                            # nil.to_s creates new string object "" (the empty string)                            # .sub! modifies new string object in place                            # edited string not assigned anything, garbage collected later puts b #=> nil             # b still assigned nil 

we observe b never changed sub!. solely object returned b.to_s changed (but discarded).


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -