I have this code to split a string into groups of 3 bytes:
str="hello"
ix=0, iy=0
bytes=[]
tby=[]
str.each_byte do |c|
if iy==3
iy=0
bytes[ix]=[]
tby.each_index do |i|
bytes[ix][i]=tby[i]
end
ix+=1
end
tby[iy]=c
iy+=1
end
puts bytes
I've based it on this example: http://www.ruby-forum.com/topic/75570
Howe开发者_JAVA技巧ver I'm getting type errors from it. Thanks.
ix = 0, iy = 0
translates to ix = [0, (iy = 0)]
, which is why you get a type error.
However there is a less "procedural" way to do what you want to do:
For ruby 1.8.7+:
"hello world".each_byte.each_slice(3).to_a
#=> [[104, 101, 108], [108, 111, 32], [119, 111, 114], [108, 100]]
For ruby 1.8.6:
require 'enumerator'
"hello world".enum_for(:each_byte).enum_for(:each_slice, 3).to_a
Your problem is the line
ix=0, iy=0
It sets the value of ix to an array of twice 0, and iy to 0. You should replace it by
ix, iy = 0, 0
精彩评论