On Tue, Nov 29, 2011 at 6:59 PM, Adam Mulan <amulan91 / gmail.com> wrote:
> Hello,
> I have prepared the following code (it almost works for even size
> strings). I wanna create 2-chars vectors from ASCII codes and push them
> on the stack, then proceed by algebra functions (Hill cipher). I don't
> want use encryption library, because it's academic exercise (I can use
> any language).
>
> #!/usr/bin/env ruby
>
> require 'matrix'
>
> print "Message: "
> msg =3D gets.chomp
>
> # stack with matrices
> stack =3D []
> # make matrix with column
> i =3D 0
> column =3D [0, 0]
> msg.each_byte do |char|
> =A0# create two-element vector
> =A0column[0] =3D char if i =3D=3D 0
> =A0if i =3D=3D 1
> =A0 =A0column[1] =3D char
> =A0 =A0# put vector on stack
> =A0 =A0puts "Input data: #{column[0]}, #{column[1]}"
> =A0 =A0tmp =3D Matrix[column[0], column[1]]

I get an error here, cause Matrix#[] is expecting an array.

> =A0 =A0puts "Output data: #{tmp[0,0]} #{tmp[0,1]}"
> =A0 =A0stack.push(tmp)
> =A0 =A0i =3D 0
> =A0 =A0next
> =A0end
> =A0i +=3D 1
> end
>
> The output data is invalid, i don't store input data in tmp Matrix class
> variable. Why?

Your algorithm can be made simpler, using each_slice:


#!/usr/bin/env ruby

require 'matrix'

print "Message: "
msg =3D gets.chomp

# stack with matrices
stack =3D []
msg.each_byte.each_slice(2) do |two_char_array|
  stack.push Matrix[two_char_array]
end
p stack

Typing "test" as the message I get:

[Matrix[[116, 101]], Matrix[[115, 116]]]

Hope this helps.

Jesus.