Steve_D
Steve_D

Reputation: 553

Split a String at a certain point

I am trying to parse a users email address if the length is greater than 18 characters. I want to remove all characters after the 18th character. Is there a way to split a string at a certain index without having to first turn it into an array?

Upvotes: 0

Views: 131

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118289

You can use regex also for your purpose. This would be a fun, but not to show, that it is a better answer although :-

"Now is"[/.{,18}/] # => "Now is"

String#[] method takes regex as an argument

If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.

Upvotes: 2

Santhosh
Santhosh

Reputation: 29144

You can do

> "a very very very looooooooooooong string"[0, 18]
#=> "a very very very l"

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110725

s[0,18] will do it.

"Now is"[0,18] #=> "Now is"
"Now is the time for all good people"[0,18] #=> "Now is the time fo"

Upvotes: 4

Related Questions