gpt4 book ai didi

Ruby 占用双倍的 RAM

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:58 24 4
gpt4 key购买 nike

我正在用我的家庭服务器尝试一些事情,并编写了一个小的 ruby​​ 程序来按给定的数量填充 RAM。但实际上我必须将要放入 RAM 的字节数减半。我在这里遗漏了什么还是这是一个错误?

这里是代码:

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

想象一下,每一行的 "* 0.5" 都不会存在。

我确实在 IRB 中对其进行了测试,并且刚刚创建了一个新的 RAM 对象并用 1000 兆字节的数据填充了它。在我的例子中,它实际上用 2000 兆字节的数据填充了 RAM,所以我确实在每一行中添加了时间 0.5,但这不是解决方案。

最佳答案

当我运行它时,我得到:

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

我认为问题是缺少编码检查。

我在 US-ASCII(一个字符 = 1 字节)中运行了我的测试。

如果您以 UTF-16 运行它,您就会对您的问题有一个解释。

你能试试下面的代码来检查你的编码吗:

p Encoding.default_internal 
p Encoding.default_external

看完评论后:

脚本的结果取决于 RAM.fill_ram 的参数。您如何启动脚本 - 您多久调用一次 RAM.fill_ram

请提供完整代码。

我调用了我的例子

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

关于Ruby 占用双倍的 RAM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23175532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com