Alexandre De Angelis
Alexandre De Angelis

Reputation: 83

How to make structures in Ruby?

I'd like to know how to make structs using a class. I know this sounds a bit abstract, but this is what I'd like to achieve:

class Person < StructHelper
   string :name
   string :last_name
   int :age
   long :birth_date

   def handle()
     puts "My name is #{name} and I'm #{age} years old"
   end
end

It could be useful in binary serialization.

Please note that Marshall cannot be used because the binary format I use is very specific (ie: int is 4bytes, long is 8bytes, string is 4bytes[len]+the string itself, etc), that is why I use a class.

It kind of is the same as BinData::Structure but I'd like it to be simpler than what BinData provides and I'd like to understand how it works.

Kind regards

Upvotes: 1

Views: 153

Answers (2)

shivam
shivam

Reputation: 16506

A quick example

Struct.new("Person", :name, :last_name, :age, :birth_date)
a = Struct::Person.new("Abc", "XYZ", 12, 121)
#=> #<struct Struct::Person name="Abc", last_name="XYZ", age=12, birth_date=121>

Serialization using Marshal#dump

serialized_object = Marshal::dump(a)

Upvotes: 1

peter
peter

Reputation: 42192

Do you mean creating a class from a struct ? Like below ? I recently read somewhere that would be a bad practice, Perhaps we can start a discussion here if that is realy the case.

# approach 1
Team = Struct.new(:players, :coach)
class Team
  def slogan
    "A stitch in time saves nine"
  end
end
some_team = Team.new(some_players, some_coach)

# approach 2
class Team < Struct.new(:players, :coach)
  def slogan
    "It takes one to know one"
  end
end

# approach 3
Foo = Struct.new(:x) do
  def hello
    "hi"
  end
end

Upvotes: 1

Related Questions