假设我有一组Twitter帐户名:

string = %w[example1 example2 example3 example4 example5 example6 example7 example8 example9 example10 example11 example12 example13 example14 example15 example16 example17 example18 example19 example20]

以及prepend和append变量:
prepend = 'Check out these cool people: '
append = ' #FollowFriday'

我如何将它变成一个尽可能少的字符串,每一个都有140个字符的最大长度,从预置文本开始,以附加文本结尾,在Twitter帐户名称之间,都以@符号开始,并与一个空间分隔开。这样地:
tweets = ['Check out these cool people: @example1 @example2 @example3 @example4 @example5 @example6 @example7 @example8 @example9 #FollowFriday', 'Check out these cool people: @example10 @example11 @example12 @example13 @example14 @example15 @example16 @example17 #FollowFriday', 'Check out these cool people: @example18 @example19 @example20 #FollowFriday']

(帐户的顺序并不重要,因此从理论上讲,您可以尝试找到最佳顺序以最大限度地利用可用空间,但这不是必需的。)
有什么建议吗?我想我应该使用scan方法,但还没有找到正确的方法。
使用一堆循环非常简单,但我猜在使用正确的Ruby方法时,这是不必要的到目前为止,我想到的是:
# Create one long string of @usernames separated by a space
tmp = twitter_accounts.map!{|a| a.insert(0, '@')}.join(' ')
# alternative: tmp = '@' + twitter_accounts.join(' @')

# Number of characters left for mentioning the Twitter accounts
length = 140 - (prepend + append).length

# This method would split a string into multiple strings
# each with a maximum length of 'length' and it will only split on empty spaces (' ')
# ideally strip that space as well (although .map(&:strip) could be use too)
tweets = tmp.some_method(' ', length)

# Prepend and append
tweets.map!{|t| prepend + t + append}

附笔。
如果有人有更好的标题的建议,请告诉我我很难总结我的问题。

最佳答案

我会利用reduce来:

string = %w[example1 example2 example3 example4 example5 example6 example7 example8 example9 example10 example11 example12 example13 example14 example15 example16 example17 example18 example19 example20]
prepend = 'Check out these cool people:'
append = '#FollowFriday'

# Extra -1 is for the space before `append`
max_content_length = 140 - prepend.length - append.length - 1

content_strings = string.reduce([""]) { |result, target|
  result.push("") if result[-1].length + target.length + 2 > max_content_length
  result[-1] += " @#{target}"

  result
}

tweets = content_strings.map { |s| "#{prepend}#{s} #{append}" }

这将产生:
"Check out these cool people: @example1 @example2 @example3 @example4 @example5 @example6 @example7 @example8 @example9 #FollowFriday"
"Check out these cool people: @example10 @example11 @example12 @example13 @example14 @example15 @example16 @example17 #FollowFriday"
"Check out these cool people: @example18 @example19 @example20 #FollowFriday"

09-17 12:03
查看更多