假设我有一组 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 帐户名称之间- 符号并用空格分隔。像这样:
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}
附言 如果有人对更好的标题有建议,请告诉我。我很难总结我的问题。
最佳答案
String rindex
方法有一个 optional parameter您可以在其中指定从何处开始在字符串中向后搜索:
arr = %w[example1 example2 example3 example4 example5 example6 example7 example8 example9 example10 example11 example12 example13 example14 example15 example16 example17 example18 example19 example20]
str = arr.map{|name|"@#{name}"}.join(' ')
prepend = 'Check out these cool people: '
append = ' #FollowFriday'
max_chars = 140 - prepend.size - append.size
until str.size <= max_chars do
p str.slice!(0, str.rindex(" ", max_chars))
str.lstrip! #get rid of the leading space
end
p str unless str.empty?
关于ruby - 将字符串数组连接成 1 个或多个字符串,每个字符串都在一定的字符限制内(+ 前置和附加文本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16113261/