Marshal là module serialization built-in của Ruby — chuyển đổi object thành binary string (dump) và khôi phục lại (load).
Hoàn toàn Ruby-specific, không portable qua ngôn ngữ khác.
ruby
class Point
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
end
point = Point.new(3, 4)
# Serialize → binary
binary = Marshal.dump(point)
# Deserialize ← binary
restored = Marshal.load(binary)
puts restored.x # => 3Khi dùng: cache phức tạp (Rails session store mặc định là Marshal), queue serialization (Sidekiq với một số cấu hình), gRPC/IPC nội bộ Ruby process.
Khi KHÔNG dùng:
- Input từ user/network — Marshal.load trên data không tin cậy cho phép remote code execution (lỗ hổng bảo mật nghiêm trọng).
- Lưu trữ lâu dài hoặc chia sẻ với ngôn ngữ khác — dùng JSON/MessagePack.