Ruby and ASCII matrix

Hello,
I have prepared the following code (it works for even string
size for example “mamala”). I want 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 = gets.chomp

stack with matrices

stack = []

make matrix with column

i = 0
column = [0, 0]
msg.each_byte do |char|

create two-element vector

column[0] = char if i == 0
if i == 1
column[1] = char
# put vector on stack
puts “Input data: #{column[0]}, #{column[1]}”
tmp = Matrix[column[0], column[1]]
puts “Output data: #{tmp[0,0]} #{tmp[0,1]}”
stack.push(tmp)
i = 0
next
end
i += 1
end

The output data is invalid. The data stored in tmp is invalid. Why?

On Tue, Nov 29, 2011 at 6:59 PM, Adam M. [email protected] wrote:

column[0] = char if i == 0
if i == 1
column[1] = char

put vector on stack

puts “Input data: #{column[0]}, #{column[1]}”
tmp = Matrix[column[0], column[1]]

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

puts “Output data: #{tmp[0,0]} #{tmp[0,1]}”
stack.push(tmp)
i = 0
next
end
i += 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 = gets.chomp

stack with matrices

stack = []
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.

Thank you.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs