What is the equivalent of Nodejs Buffer in Ruby?

Ruby Strings and Arrays are Dynamic, Not Fixed-Length

There really isn't a direct comparison in Ruby's core or standard library, although I suppose you could create your own simulation of one. A Node.js Buffer is a fixed-length sequence of bytes. Depending on what that means for your use case, you can use one or more of:

  • String#bytes
  • String#byteslice
  • Array#pack and String#unpack

to access the stored bytes, but neither String nor Array objects in Ruby are really fixed-length unless you freeze them. However, frozen objects are (for most purposes) immutable, so that's really not quite the same thing. As a result, it's basically up to you to truncate, slice, replace by index, or otherwise drop elements to maintain a "fixed size."

If you plan to do this a lot, you could create a subclass of String or Array with a getter or setter method that truncates the contents of an instance variable to your desired size every time you access it. That's most likely your best bet, although it's certainly possible someone has already written a gem that provides this functionality. The Ruby Toolbox and RubyGems.org are your best bets for searching for gems that provide implementations of fixed-size or circular buffers if you don't want to implement your own, but the options and quality will vary greatly as they aren't part of Ruby's built-in classes.