manejo interpolar contar caracteres cadenas ruby string function substr chars

contar - interpolar en ruby



Ruby: cómo seleccionar algunos caracteres de la cadena (2)

Estoy tratando de encontrar una función para seleccionar, por ejemplo, los primeros 100 caracteres de la cadena. En PHP, existe la function substr

Ruby tiene alguna función similar?


Usando el operador []:

foo[0,100] # Get the first 100 characters starting at position 0 foo[0..99] # Get all characters in index range 0 to 99 (inclusive) foo[0...100] # Get all characters in index range 0 to 100 (exclusive)

Usando el método .slice:

foo.slice(0, 100) # Get the first 100 characters starting at position 0 foo.slice(0...100) # All identical to []

Y para completar:

foo[0] # Returns the first character (doh!) foo[-100,100] # Get the last 100 characters in order. Negative index is 1-based foo[-100..-1] # Get the last 100 characters in order foo[-1..-100] # Get the last 100 characters in reverse order foo[-100...foo.length] # No index for one beyond last character