代码
def split_description(description, first_n)
@description_first, @description_remain =
case description.count("\n")
when 0..first_n
[description, '']
else
partition_description(description, first_n)
end.map(&:to_html)
end
def partition_description(description, first_n)
return ['', description] if first_n.zero?
offset = 0
description.each_line.with_index(1) do |s,i|
offset += s.size
return [description[0,offset], description[offset..-1]] if i == first_n
end
end
我假设to_html('') #=> '',但如果不是这样,修改很简单。
示例
为了看到to_html的效果,我们就这么定义吧。
def to_html(description)
description.upcase
end
description =<<_
It was the best of times
it was the worst of times
it was the age of wisdom
it was the age of fools
_
split_description(description, 0)
@description_first
#=> ""
@description_remain
#=> "IT WAS THE BEST OF TIMES\n..WORST OF TIMES\n..AGE OF WISDOM\n..AGE OF FOOLS\n"
split_description(description, 1)
@description_first
#=> "IT WAS THE BEST OF TIMES\n"
@description_remain
#=> "IT WAS THE WORST OF TIMES\n..AGE OF WISDOM\n..AGE OF FOOLS\n"
split_description(description, 2)
@description_first
#=> "IT WAS THE BEST OF TIMES\nIT WAS THE WORST OF TIMES\n"
@description_remain
#=> "IT WAS THE AGE OF WISDOM\nIT WAS THE AGE OF FOOLS\n"
split_description(description, 3)
@description_first
#=> "IT WAS THE BEST OF TIMES\n..WORST OF TIMES\n..AGE OF WISDOM\n"
@description_remain
#=> "IT WAS THE AGE OF FOOLS\n"
split_description(description, 4)
@description_first
#=> "IT WAS THE BEST OF TIMES\n..WORST OF TIMES\n..AGE OF WISDOM\n..AGE OF FOOLS\n"
@description_remain
#=> ""
说明
首先,description 似乎是一个保存字符串的局部变量。如果是这样,它必须是方法的参数(连同first_n)。
def split_description(description, first_n)
我们想给两个实例变量赋值,所以让我们开始写
@description_first, @description_remain =
实际上有两个步骤:获取所需的字符串,然后将它们映射到to_html。所以我们先把注意力集中在第一步。
我们现在以字符串中的行数为条件
case description.count("\n")
首先,我们来处理字符串不包含换行符的情况
when 0
[description, '']
如果字符串为空,则为['', ''];否则它将包含一个没有换行符的字符串。
接下来,假设字符串中的换行数介于 1 和 first_n 之间。在这种情况下,@description_first 是整个字符串,@description_remain 是空的。
when 1..first_n
[description, '']
由于when 0 和when 1..first_n 返回相同的二元数组,我们可以将它们组合起来:
when 0..first_n
[description, '']
到目前为止,first_n 小于换行符的数量。对于换行数大于first_n的情况,我使用了另一种方法。
else
partition_description(description, first_n)
partition_description 只是确定first_nth 换行符到description 的偏移量,然后相应地对字符串进行分区。
最后,我们需要结束case语句,映射to_html返回的两个字符串数组,结束方法
end.map(&:to_html)
end
正如我之前提到的,我假设to_html('') #=> ''。在我看来,这似乎是处理空字符串的最佳场所。
请注意,我直接处理了字符串,而不是将字符串拆分为行,操作这些行然后重新加入它们。