String.left?


(Philip Mak) #1

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.:

“1234567890”.left(4) => "1234"
“x”.left(4) => “x”


(Nikodemus Siivola) #2

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 :wink:

– Nikodemus

···

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.:


(k) #3

“1234567890”.slice(0,4)
or
"1234567890"[0…4]
or
"1234567890"[0,4]
or
see http://www.rubycentral.com/book/ref_c_string.html

“Philip Mak” pmak@animeglobe.com wrote in message
news:20020609234140.GI9947@trapezoid.interserver.net

···

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.:

“1234567890”.left(4) => "1234"
“x”.left(4) => “x”


(Joel VanderWerf) #4

Nikodemus Siivola 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 :wink:

…and decide how you want to handle strings shorter than 4 :slight_smile:

p “123”[0,4] # ==> “123”

p “123”[0…3] # ==> “123”

p “123”[/^.{4}/] # ==> nil

p “123”[/^.{0,4}/] # ==> “123”

···

On Mon, 10 Jun 2002, Philip Mak wrote: