假设我有一组 Twitter 帐户名称:
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'
如何将其转换为尽可能少的字符串数组,每个字符串的最大长度为 140 个字符,从前置文本开始,以附加文本结尾,在 Twitter 帐户名称之间都以 @-sign 和用空格隔开。像这样:
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}
PS如果有人对更好的标题有建议,请告诉我。我很难总结我的问题。