roman
roman

Reputation: 5210

Delete n characters from string ending to make it a string with exact length

How can i elegantly delete all the characters from the end of the string to make it match the exact length.

For example i have a string 1234567.... I need a string with length 6, so i need to delete 7.... Note 7... may contain any amount of symbols.

Upvotes: 0

Views: 99

Answers (2)

fl00r
fl00r

Reputation: 83680

string = "abcdefghigkl"
# get first 7 chars without affecting on original string
new_string = string[0,6]
# force remove from 7th char
string[6..-1] = ""
string
#=> "abcdef"

Upvotes: 2

Michael Kohl
Michael Kohl

Reputation: 66837

You can index a string with a range:

s = "12345678"
s[0...6] # => "123456"

Upvotes: 3

Related Questions