How to truncate strings in Ruby?

M

Marston A.

So I'd think this is a very simple question, I've searched around the
manual and google but couldn't really find it.

So what is the method to truncate a string in Ruby? Similar to the
truncate(@text, 20) helper method in Rails? To get the first 20
characters of a string for example. Thanks in advanced
 
P

Phillip Hutchings

So I'd think this is a very simple question, I've searched around the
manual and google but couldn't really find it.

So what is the method to truncate a string in Ruby? Similar to the
truncate(@text, 20) helper method in Rails? To get the first 20
characters of a string for example. Thanks in advanced

Slice it, just remember it's 0 indexed.
s = '0123456789'
s = s[0..4]
=> '01234'
 
L

Logan Capaldo

So I'd think this is a very simple question, I've searched around the
manual and google but couldn't really find it.

So what is the method to truncate a string in Ruby? Similar to the
truncate(@text, 20) helper method in Rails? To get the first 20
characters of a string for example. Thanks in advanced

@text[0...20]

@text[0, 20]

@text.slice(0, 20)

@text.slice!(0, 20) # modifies @text in place to become it's
"truncation"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top