在Ruby中,一个内容限制字数小于N个字符?

时间:2010-08-10 03:20:39

标签: ruby arrays

限制单词数组的最简单方法是什么,当单词连接时,结果数组少于40个字符?像这样的东西:

words = ["ruby", "rails", "jquery", "javascript", "html"]
words.join.length #=> 29
words.join(", ").length #=> 37
words = ["ruby", "rails", "jquery", "javascript", "html", "css", "api"]
words.join.length #=> 35
words.join(", ").length #=> 47
words.chunk(:max_chars => 40) #=> ["ruby", "rails", "jquery", "javascript", "html"]

更新

到目前为止:

def chop(array, separator = "", max = 40)
  result = []
  array.each do |word|
    break if (result.join(separator).length + word.length > max)
    result << word 
    result
  end
  result
end

4 个答案:

答案 0 :(得分:1)

这是一种有趣的方式,您需要积极的支持:

require 'active_support'
class Array
  def chunk(sep = "", max = 40)
    self.inject([]){|m,n| (m+[n]).sum(&:size)+sep.size*m.size-1<max ? m<<n : m}
  end
end

现在:

["ruby", "rails", "jquery", "javascript", "html", "css", "api"].chunk(", ") #=> ["ruby", "rails", "jquery", "javascript", "html"]

答案 1 :(得分:1)

你的略有不同:

result = input.inject([]){|r,word|r<<word if r*separator+word.length < max}

答案 2 :(得分:1)

太糟糕了有一个fencepost条件,否则这将是一个更清晰的代码与take_while方法

def chop(array, separator = "", max_size = 40)
  so_far = 0
  sep = separator.size
  array.take_while{|word| (so_far += word.size + sep) <= max_size + sep }
end

它检查它是否小于或等于max_size + sep以补偿我们为每个单词添加分隔符,即使最后一个单词不需要它。

答案 3 :(得分:1)

def chop(arr, sep = "", max = 40)
  max += sep.size
  arr.take_while{|x| (max -= x.size + sep.size) >= 0 }
end