来自字符串的位数组

Bit array from string

我有一个字符串:

cipher = "0111101110010111001001010000000110101000001000111101110000110101100100001100101100000"

我想将它切片并存储在数组中,如下所示: ["01111011", "10010111" ...]

我试过这段代码,但出现错误:

"cz.rb:16:in <main>': undefined methodpush' for nil:NilClass (NoMethodError)"

i,j = 0,0
cipher_byte = []
while i < cipher.length
  if i != 0 and i % 8 == 0
   j+=1
  end
  cipher_byte[j].push(cipher[i])
  p cipher_byte
  i+=1
end

这是怎么回事? 这是 ruby.

您正在尝试推送到 cipher_byte[j],正如错误告诉您的那样,它尚未设置值。 (在循环的第一次迭代中,您可以想象 cipher_byte 的长度为 0,因为它被设置为 []。因此,您还不能使用 [j] 对其进行索引。)

您可能想要 cipher_byte.push,而不是试图推到特定位置。在 Ruby 中,.push 中的数组会将那个值添加到数组的末尾;您不需要使用 j.

来引用该位置

您正在索引一个空数组 (cipher_byte) 并得到 nil。然后在 nil

的实例上调用 push

您需要在每次 etc 迭代时创建一个新数组,然后将该子数组推送到主数组。

最简单:

cipher.each_char.each_slice(8).map(&:join)

更快:

(0...cipher.length).step(8).map { |i| cipher[i, 8] }

更少的代码意味着更少的地方可以隐藏错误(只要代码仍然可读)。 Ruby 提供了许多惯用语和方法,使程序员的事情变得非常直观和容易。带有计数器的 while 循环很少 Rubyish;带有无条件递增计数器的 while 循环永远不会。

cipher.scan(/.{8}/)
  #=> ["01111011", "10010111", "00100101", "00000001", "10101000",
  #    "00100011", "11011100", "00110101", "10010000", "11001011"]