From: Joel VanderWerf Date: 2002-06-10T09:03:31+09:00 Subject: Re: String.left? Nikodemus Siivola wrote: > > On Mon, 10 Jun 2002, Philip Mak wrote: > > > Is there a function that acts like String.left? I'd like to be able to > > get the leftmost x characters of the string. e.g.: > > String#slice and it's synonym String#[ ] > > ~$ ruby -e 'p "1234567890"[0,4]' # from pos 0, 4 chars > "1234" > ~$ ruby -e 'p "1234567890"[0..3]' # chars of given range > "1234" > ~$ ruby -e 'p "1234567890"[/^.{4}/]' # with a regexp > "1234" > > Pick your favorite ;) ..and decide how you want to handle strings shorter than 4 :) p "123"[0,4] # ==> "123" p "123"[0..3] # ==> "123" p "123"[/^.{4}/] # ==> nil p "123"[/^.{0,4}/] # ==> "123"