Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

325
Views
¿Cómo dividir texto largo en líneas más pequeñas por palabras en Ruby/Rails?

¿Cómo dividir texto largo en líneas más pequeñas por palabras? Idealmente, necesito un método como

 def text_splitter(text, line_size = 5) # ... end text_splitter("abcde text longword") # => ["ab c", "de ", "text ", "longword"]
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Rails viene con el asistente word_wrap que puede dividir líneas largas en función de un ancho de línea determinado. Siempre se divide en espacios en blanco para que las palabras largas no se dividan/corten.

En rails/console :

 lines = helper.word_wrap("abcde text longword", line_width: 5) #=> "abc\nd e\ntext\nlongword" puts lines

Producción:

 abc de text longword

Tenga en cuenta que devuelve una cadena, no una matriz.

over 4 years ago · Santiago Trujillo Report

0

Eso se puede hacer en Ruby puro de la siguiente manera 1 .

 def text_splitter(text, line_size) text.gsub(/(?:.{1,#{line_size}}|\S+)\K(?:$|\s)/, "\n") end
 text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
 puts text_splitter(text, 30) 0 1 2 3 123456789012345678901234567890 Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
 puts text_splitter(text, 20) 0 1 2 12345678901234567890 Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
 puts text_splitter(text, 10) 0 1 1234567890 Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
 puts text_splitter(text, 8) 0 12345678 Beware the Jabberwock, my son! The jaws that bite, the claws that catch!

La expresión regular se puede dividir de la siguiente manera (para line_size = 10 ):

 (?: # begin non-capture group .{1,10} # match 1-10 chars | # or \S+ # match >= 1 non-whitespace chars ) # end non-capture group \K # reset start of match and discard all chars previously matched (?:$|\s) # match the end of the string or a whitespace chars

1. El texto de muestra es del poema de Lewis Carrol, "Jabberwocky".

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!