Format output to 40 characters long per line

后端 未结 3 624
长发绾君心
长发绾君心 2021-01-26 08:41

I\'m fairly new to Ruby and I\'ve been searching Google for a few hours now. Does anyone know how to format the output of a print to be no more than 40 characters long?

3条回答
  •  渐次进展
    2021-01-26 08:59

    Ruby 1.9 (and not overly efficient):

    >> x.join(" ").each_char.each_slice(40).to_a.map(&:join)
    => ["This is a simple sentence. This simple s", "entence appears on three lines."]
    

    The reason your solution doesn't work is that all the individual strings are shorter than 40 characters, so n[0..40] always is the entire string.

提交回复
热议问题