Robert McHardy
Robert McHardy

Reputation: 164

Ruby takes the doubled amount of RAM it should

I was trying things out with my homeserver and wrote a little ruby program that fills up the RAM by a given amount. But actually I have to halve the amount of bytes I want to put into the RAM. Am I missing something here or is this a bug?

Here the code:

class RAM

  def initialize
    @b = ''
  end

  def fill_ram(size)
    puts 'Choose if you want to set the size in bytes, megabytes or gigabytes.'
    answer = ''
    valid = ['bytes', 'megabytes', 'gigabytes']
    until valid.include?(answer)
      answer = gets.chomp.downcase
      if answer == 'bytes'
        size = size * 0.5
      elsif answer == 'megabytes'
        size = size * 1024 * 1024 * 0.5
      elsif answer == 'gigabytes'
        size = size * 1024 * 1024 * 1024 * 0.5
      else
        puts 'Please choose between bytes, megabytes or gigabyte.'
      end
    end
    size1 = size
    if @b.bytesize != 0
      size1 = size + @b.bytesize
    end
    until @b.bytesize == size1
      @b << '0' * size
    end
    size = 0
  end

  def clear_ram
    exit
  end

  def read_ram
    puts 'At the moment this program fills ' + @b.bytesize.to_s + ' bytes of RAM'
  end

end

Just imagine that the "* 0.5" at each line wouldn't be there.

I did test it in IRB and just created a new RAM object and filled it with 1000 Megabytes of data. In my case it filled the RAM actually with 2000 Megabytes of data, so I did add the times 0.5 to each line, but that can't be the solution.

Upvotes: 1

Views: 84

Answers (1)

knut
knut

Reputation: 27845

When I run it I get:

Choose if you want to set the size in bytes, megabytes or gigabytes.
bytes
At the moment this program fills 512 bytes of RAM

I think the problem is the missing check for the encoding.

I ran my test in US-ASCII (One character = 1 Byte).

If you run it in UTF-16 you have an explanation for your problem.

Can you try the following code to check your encoding:

p Encoding.default_internal 
p Encoding.default_external

After reading the comment:

The result of your script depends on the parameter of RAM.fill_ram. How do you start your script - and how often do you call RAM.fill_ram?

Please provide the full code.

I called my example with

r = RAM.new
r.fill_ram(1024)
r.read_ram

Upvotes: 3

Related Questions