2

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

However I'm getting type errors from it. Thanks.

unknown
  • 175
  • 1
  • 1
  • 5
  • can't convert Array into Integer.. but the example is almost exactly the same and doesn't get these type errors – unknown Nov 29 '09 at 16:39

2 Answers2

6

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
sepp2k
  • 363,768
  • 54
  • 674
  • 675
2

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
j.p.
  • 1,031
  • 1
  • 18
  • 25