How to wrap a string into lines of width w in Ruby

1 Answer

0 votes
# Wrap a string into lines of maximum width `width`
# This version avoids breaking words unless a word itself is longer than `width`
def wrap(text, width)
  lines = []       # Array to store the final wrapped lines
  current = ""     # The line currently being built

  # Split the text into words and iterate through them
  text.split.each do |word|
    # If the current line is empty, start it with the word
    if current.empty?
      current = word

    # If adding the next word stays within the width, append it
    elsif current.length + 1 + word.length <= width
      current << " " << word

    # Otherwise, push the current line and start a new one
    else
      lines << current
      current = word
    end
  end

  # Add the last line if not empty
  lines << current unless current.empty?

  lines
end

# --- Usage ---
if __FILE__ == $0
  text = "Ruby is a dynamic, open source programming language with a focus on simplicity and productivity."
  width = 25

  puts "Wrapped text (width = #{width}):"
  puts "-" * 40
  wrap(text, width).each { |line| puts line }
end


# run:
# 
# Wrapped text (width = 25):
# ----------------------------------------
# Ruby is a dynamic, open
# source programming
# language with a focus on
# simplicity and
# productivity.
# 

 



answered 2 hours ago by avibootz
...