From: Robert Klemme Date: 2008-08-20T16:36:11+09:00 Subject: Re: Cut a string if length > n 2008/8/20 Pål Bergström : > Robert Klemme wrote: > >> Pal, it seems we haven't seen the complete specification of what you >> want to do. It seems that not only length is a condition but also >> positions of spaces. > > Hi. My app shows data in a list from a table called messages but only a > fragment of it if it's to long. > > My solution seems to work fine. What do you think of it? Will it always > work? > > lastspace = message.message[0..70].rindex(" ") > puts message.message[0..lastspace.to_i] > > It doesn't do anything for non existing messages and text that isn't > that long as 70. And it finds the last space. We might have long words > in Swedish, but not that long :-) There will always be a space somewhere > in the end where it can cut it without cutting and leave strange > question marks as it cuts a swedish character (as Latin1 I guess). As has been mentioned you probably should use the ... range form because otherwise you'll have a space at the end. But this does not work in light of multiple spaces either. I'd probably choose a solution with regular expressions: 09:36:10 RKlemme$ /c/Temp/truncate.rb ["aaaaa", 5, "a", "", "aaaaa", "aaaaa", "aaaaa"] ["aaaaa bbbbb", 11, "aaaaa ", "aaaaa", "aaaaa bbbbb", "aaaaa bbbbb", "aaaaa"] ["aaaaa bbbbb ccccc", 17, "aaaaa bbbbb ", "aaaaa bbbbb", "aaaaa bbbbb ", "aaaaa bbbbb", "aaaaa bbbbb"] ["aaaaa bbbbb ccccc ddddd", 23, "aaaaa bbbbb ", "aaaaa bbbbb", "aaaaa bbbbb ", "aaaaa bbbbb", "aaaaa bbbbb"] ["aaaaa", 5, "a", "", "aaaaa", "aaaaa", "aaaaa"] ["aaaaa bbbbb", 12, "aaaaa ", "aaaaa ", "aaaaa bbbbb", "aaaaa bbbbb", "aaaaa "] ["aaaaa bbbbb ccccc", 19, "aaaaa ", "aaaaa ", "aaaaa ", "aaaaa bbbbb", "aaaaa bbbbb"] ["aaaaa bbbbb ccccc ddddd", 26, "aaaaa ", "aaaaa ", "aaaaa ", "aaaaa bbbbb", "aaaaa bbbbb"] Here's the code that you can use to play around with various solutions: 09:37:02 RKlemme$ cat /c/Temp/truncate.rb #!/bin/env ruby WD = 5 LIM = 12 strings = (0..3).map do |i| (0..i).map do |ii| (?a + ii).chr * WD end.join " " end strings.concat strings.map {|s| s.gsub /\s/, ' '} strings.each do |str| p [ str, str.length, str[0..str[0...LIM].rindex(' ').to_i], str[0...str[0...LIM].rindex(' ').to_i], str[%r{\A.{0,#{LIM}}\b(?!\s)}], str[%r{\A.{0,#{LIM - 1}}\S}], # <- my choice str[%r{\A(.{0,#{LIM}})\s}, 1] || str, ] end Kind regards robert -- use.inject do |as, often| as.you_can - without end