Cómo obtener una subcadena de texto?


Tengo texto con longitud ~700. ¿Cómo obtengo solo ~30 de sus primeros caracteres?

 139
Author: user664833, 2011-05-31

5 answers

Si tiene su texto en la variable your_text, puede usar:

your_text[0..29]
 207
Author: Matteo Alessani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-17 10:25:16

Uso String#slice, también alias [].

a = "hello there"
a[1]                   #=> "e"
a[1,3]                 #=> "ell"
a[1..3]                #=> "ell"
a[6..-1]               #=> "there"
a[-3,2]                #=> "er"
a[-4..-2]              #=> "her"
a[12..-1]              #=> nil
a[-2..-4]              #=> ""
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil
 180
Author: Simone Carletti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-21 09:41:33

Desde que lo etiquetaste Rails, puedes usar truncate:

Http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

Ejemplo:

 truncate(@text, :length => 17)

Extracto es bueno saber también, le permite mostrar un extracto de un texto como así:

 excerpt('This is an example', 'an', :radius => 5)
 # => ...s is an exam...

Http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt

 24
Author: apneadiving,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-16 17:51:11

Si lo necesitas en rails puedes usar primero (código fuente )

'1234567890'.first(5) # => "12345"

También Hay última (código fuente)

'1234567890'.last(2) # => "90"

Alternativamente marque desde/hasta (código fuente):

"hello".from(1).to(-2) # => "ell"
 6
Author: Aray,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-25 10:34:49

Si quieres una cadena, entonces las otras respuestas están bien, pero si lo que buscas son las primeras letras como caracteres puedes acceder a ellas como una lista:

your_text.chars.take(30)
 0
Author: user12341234,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-21 23:31:54