开发者

Which is the equivalent in Ruby to the Delphi SizeOf function?

开发者 https://www.devze.com 2023-01-05 08:40 出处:网络
I want to get the number of bytes occupied by a variable or type in Ruby.Is ther开发者_JAVA百科e an equivalent to the SizeOf function in Ruby on Rails?As you see from the comments, there is no such me

I want to get the number of bytes occupied by a variable or type in Ruby. Is ther开发者_JAVA百科e an equivalent to the SizeOf function in Ruby on Rails?


As you see from the comments, there is no such method in Ruby. Since you can't manipulate the memory directly in Ruby and there are no explicit "simple" types (everything is an object), and due to the dynamic nature of Ruby, this method wouldn't be very useful anyway.

There is an exception of sorts with the String class. Since in Ruby a string is a sequence of bytes, String#size will return the size of the data in the string.

This should be sufficient for practical purposes, but it is not the number of bytes in memory - the String object will have other internal variables in addition to the data itself.

Also remember that all classes and objects can be modified dynamically in Ruby during runtime, which can change the amount of memory used. Just think of methods that add additional instance variables to an object that weren't there before.


If you're trying to make things compatible with your Delphi code, than finding Ruby's sizes wouldn't help you at all. You need to take Delphi's sizes in your Ruby code. Since Delphi is statically typed, SizeOf is really a convenience - just make a table of the Delphi types and corresponding sizes. If you have an array, multiply the value from the table with the number of elements.


The Scalar types are defined in ruby.c. I don't know of a way to learn their widths from within Ruby.

Added:

You could write a C program that uses ruby.c to determine the scalar sizes. Then call your C program from your Ruby sw.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号