A Rubyist's Walk Along the C-side (Part 4): Primitive Data Types

submited by
Style Pass
2021-06-05 18:00:07

In the previous article, you saw how to call Ruby methods in C extensions. In this article, we’ll look at the primitive data types in the Ruby C API.

In Ruby, everything is an object. However, that is not true when writing a C extension as not all types are created equal. For the more “primitive” types, there are often more efficient ways to manipulate them than to call the Ruby method. For example, there’s a more efficient way to get an element at a particular index in Ruby arrays in C than to call Array#[].

Every type that is listed in the union of the RVALUE struct is a primitive data type (if you’re interested in what the RVALUE struct is and how the garbage collector works in Ruby, take a look at my article titled “Peter’s Adventures in Ruby: Garbage Collection in Ruby”). The primitive data types are the following:

All the types above are “heap allocated” in Ruby, meaning that they require memory allocation and are managed by the garbage collector. However, Ruby also has the concept of immediates, which doesn’t even require an object allocation! Fixnum (i.e. small integer values), is represented as an immediate. But how does it store data without allocating an object? Remember that the VALUE type is an unsigned long? Fixnum takes advantage of that by setting a special bit in the VALUE and then it’s able to directly store the integer value in the VALUE. In addition to Fixnum, Ruby’s true, false, and nil types are also represented using immediates.

Leave a Comment