简体   繁体   English

Ruby-数组中的转义字符引发扫描

[英]Ruby - Escape characters in array throwing off scan

I'm working on a simulation type thing based around arrays. 我正在研究基于数组的模拟类型的东西。 I'm trying to make it so I can colour code the items in the array however for some reason when I write it out, the formatting is way off. 我正在尝试使其能够对数组中的项目进行颜色编码,但是由于某种原因,当我将其写出时,格式已无法使用。

I believe this to be to do with the escape characters throwing off the scan (hence the title). 我相信这与转义符脱离扫描(因此标题)有关。

I've currently got this, (only relevant bits shown) 我目前有这个,(仅显示相关位)

@width = 80
puts @world.join("").scan(/.{#{@width}}|.+/).join("\n\r")

Inside the array, I have strings and on some I have escape characters such as 在数组内部,我有字符串,并且在某些字符串上有转义字符,例如

"\\033[41mI\\033[0m"

Any ideas as to how I can fix this? 关于如何解决此问题的任何想法?

I can only guess but I think the escape parts are still being counted into the length when I call the scan on the array. 我只能猜测,但是我认为当我在数组上调用扫描时,转义部分仍被计入长度。

Thanks 谢谢

You are right, the escape sequences count into the length of the string: 没错,转义序列会计入字符串的长度:

str = "\033[41mI\033[0m"
str.size                 #=> 10
str.scan(/./).to_a       #=> ["\e", "[", "4", "1", "m", "I", "\e", "[", "0", "m"]

The reason why your code fails is that you are using the regex to split the joined string up again, where one cell of the world suddenly occupies ten characters instead of just one. 您的代码失败的原因是您使用正则表达式再次拆分了连接的字符串,其中一个世界的单元格突然占据了十个字符,而不仅仅是一个字符。 So, @width actually refers to the number of cells, not to the number of characters. 因此, @width实际上是指单元数,而不是字符数。 As an alternative approach to building the output I suggest this method: 作为构建输出的替代方法,我建议使用以下方法:

puts @world.each_slice(@width).map(&:join).join("\n\r")

It builds a nested array first, where each subarray consists of the same number of elements. 它首先构建一个嵌套数组,其中每个子数组由相同数量的元素组成。 This approach works as long as each cell only contains one visible character, which I simply assumed. 只要每个单元格只包含一个可见字符(我只是简单假设),这种方法就可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM