Ruby !sub returning strange null -


i don't understand result of first line. it's supposed return file name without extension if file has one. can explain me why , tell me more proper here?

irb(main):003:0> 'fafeafeafewafeawfeaw'.sub!(/\.[^\.]*$/, '') => nil irb(main):004:0> '.fafeafeafewafeawfeaw'.sub!(/\.[^\.]*$/, '') => "" irb(main):005:0> 'fafeafeafewafea.wfeaw'.sub!(/\.[^\.]*$/, '') => "fafeafeafewafea" 

it documented sub! (like many of ! string operations) return nil if no change made.

from docs

performs substitutions of string#sub in place, returning str, or nil if no substitutions performed.

instead use regular sub. in case bang (!) unnecessary.

'fafeafeafewafeawfeaw'.sub(/\.[^\.]*$/, '')

bang methods

the difference between sub , sub! subtle. in ruby in general, non bang (!) version of method safer. since convention bang means method has more side affects.

in case of string functions (and many array/enumerable functions) bang means method operates on contents of caller, instead of making (and returning) copy.

s = 'fafafa' puts s #=> 'fafafa'  puts s.sub(/fa/, 'fo') #=> 'fofofo'  puts s #=> 'fafafa'  puts s.sub!(/fa/, 'fo') #=> 'fofofo'  puts s #=> 'fofofo' 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -