0

I am very new to ruby and am currently trying to write a simple ruby program that reads in 1 byte blocks from a file and generates a frequency list of how many times its seen each block. However, to start off with I am simply trying to index an array of 256 bytes corresponding to each possible byte value with the 1 byte that I read in.

The problem, it seems, is that the to_i function doesn't convert characters based on their binary value, i.e. 'A' becomes 0 instead of it's ascii coded 65. Is there some other function built into ruby I can use here?

freq = Array(0..255)

File.open('temp.dat') do |file|
  until file.eof?
    buf = file.read(1)
    puts "#{freq.at(buf.to_i)}"
  end
end

2 Answers 2

1

You are looking for String#ord method:

#                   ⇓⇓⇓
puts "#{freq.at(buf.ord)}"
Sign up to request clarification or add additional context in comments.

Comments

0

You can do either of the followings:--

1)  puts "#{freq.at(buf.ord)}"

2) puts "#{freq.at(buf.unpack('C')[0])}"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.