我有一个字符串:
cipher = "0111101110010111001001010000000110101000001000111101110000110101100100001100101100000"
我想将其切片并像这样存储在数组中:[“ 01111011”,“ 10010111” ...]
我尝试了此代码,但出现错误:
“ cz.rb:16:in
<main>': undefined method
push'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
这怎么了?是红宝石。
cipher.each_char.each_slice(8).map(&:join)
更快:
(0...cipher.length).step(8).map { |i| cipher[i, 8] }
更少的代码意味着更少的地方可以隐藏错误(只要代码仍然可读)。 Ruby提供了许多惯用语和方法,使程序员可以非常直观,轻松地进行操作。带计数器的while
循环很少是Rubyish;具有无条件递增计数器的while
循环永远不会。
cipher_byte[j]
,因为错误告诉您,该值尚未设置为值。 (在循环的第一次迭代中,可以想象cipher_byte
的长度为0,因为它被设置为[]
。因此,您尚不能使用[j]
对其进行索引。)您可能想要cipher_byte.push
,而不是尝试将其推到特定位置。在Ruby中,数组上的.push
会将值添加到数组的末尾;您无需使用j
来引用该位置。
您将需要在每次迭代中创建一个新数组,然后将该子数组推入主数组。
cipher.scan(/.{8}/)
#=> ["01111011", "10010111", "00100101", "00000001", "10101000",
# "00100011", "11011100", "00110101", "10010000", "11001011"]