Siwei
Siwei

Reputation: 21557

What is the equivalent of Nodejs Buffer in Ruby?

I know in Nodejs there is a Buffer module:

import { Buffer } from "buffer/";

// node = ...
// labelSha = ...
Buffer.from(node + labelSha, "hex");


what's the equivalent in Ruby ?

thanks

Upvotes: 0

Views: 597

Answers (2)

Siwei
Siwei

Reputation: 21557

Thanks everyone!

after spending 2 hours, I also wrote my own version of implementation:

  def nodejs_buffer_to_hex origin_string
    i = 0 
    result = []
    temp = ""
    loop do
      break if i == origin_string.length
      temp += origin_string[i]
      if i % 2 == 1
        result << temp
        temp = ""
      end 
      i += 1
    end 

    result = result.map do |e| 
      "0x#{e}".hex
    end 
    return result
  end 

and usage:

nodejs_buffer_to_hex "ce159cf3"  # => [206,21,156,243]

Upvotes: 0

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84373

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:

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.

Upvotes: 1

Related Questions