From: dblack@... Date: 2006-07-31T07:04:20+09:00 Subject: Re: Howto Delete 3 Leftmost Characters Hi -- On Mon, 31 Jul 2006, Skeets wrote: > William James wrote: >> Skeets wrote: >>> i'm sure this is easy, but i've gone through Pickaxe's string methods, >>> searched the web and searched the groups, and i can't figure out how to >>> do this in Ruby. >>> >>> i grep a file and it returns the following string: >>> >>> #ip 127.0.0.1 >>> >>> i now want to get rid of "#ip" so i can then strip the remaining string >>> to get rid of spaces. >>> >>> however, i can't find out how to delete the 3 leftmost characters - in >>> this case "#ip". >>> >>> thanks for any tips to get this done - i would think it is a matter of >>> just knowing the correct method. >> >> irb(main):001:0> s="#ip 127.0.0.1" >> => "#ip 127.0.0.1" >> irb(main):002:0> s.slice!(0,3) >> => "#ip" >> irb(main):003:0> s >> => " 127.0.0.1" > > William, thanks. when i follow your approach, i get your result via > irb. however, i get a different result when i run code in a file. i'm > doing something different, but i don't know what. > > here is the code: > > #!/usr/bin/env ruby > > if File.exist?( "ip.txt" ) > > f = File.open("ip.txt').grep(/#ip/) > (f.to_s).slice!(0,3) > # f = f.strip > > end > > puts f # this outputs "#ip 127.0.0.1" - i was expecting it to output > "127.0.0.1" > > if i have > > f = (f.to_s).slice!(0,3) > > instead fo > > (f.to_s).slice!(0,3) > > then "puts f" prints "#ip" The reason is that when you do this: f.to_s.slice! ... you're operating on a string object other than f. Ruby first does f.to_s, which returns a new string, then does an in-place slice! operation on that string. In the f = ... example, you're reassigning to f, so now f is the new, modified string. David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy ----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <----- http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log http://www.manning.com/black => book, Ruby for Rails http://www.rubycentral.org => Ruby Central, Inc.