# How to truncate strings in Ruby?

**URL:** <https://www.ruby-forum.com/t/how-to-truncate-strings-in-ruby/99224>\
**Category:** Ruby\
**Created:** [July 21, 2006, 3:54am UTC](https://www.ruby-forum.com/t/how-to-truncate-strings-in-ruby/99224 "2006-07-21T03:54:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![marstoni](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9bcb4/32.png) [@marstoni](https://www.ruby-forum.com/u/marstoni)\
**Post date:** [July 21, 2006, 3:54am UTC](https://www.ruby-forum.com/t/how-to-truncate-strings-in-ruby/99224/1 "2006-07-21T03:54:24Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![marstoni](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9bcb4/32.png) [@marstoni](https://www.ruby-forum.com/u/marstoni)\
**Post date:** [July 21, 2006, 3:58am UTC](https://www.ruby-forum.com/t/how-to-truncate-strings-in-ruby/99224/2 "2006-07-21T03:58:42Z")

</div>

On 7/21/06, Marston A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 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’

---

<div class="post-metadata">

**Author:** ![marstoni](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9bcb4/32.png) [@marstoni](https://www.ruby-forum.com/u/marstoni)\
**Post date:** [July 21, 2006, 4:04am UTC](https://www.ruby-forum.com/t/how-to-truncate-strings-in-ruby/99224/3 "2006-07-21T04:04:56Z")

</div>

On Jul 20, 2006, at 9:54 PM, Marston A. wrote:

> 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
> 
> –  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

@text[0…20]

@text[0, 20]

@text.slice(0, 20)

@text.slice!(0, 20) # modifies @text in place to become it’s  
“truncation”
