Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple data structure in Ruby equivalent to Java

Tags:

java

ruby

In Java if I want a simple data structure I would simply declare it in a class something like this

class MySimpleStructure{
   int data1;
   int data2;
   MyOtherDataStructure m1;
}

Then I would later use it in my program,

MySimpleStructure s1 = new MySimpleStructure();
s1.data1 = 19;
s1.m1 = new MyOtherDataStructure();

How to do an equivalent implementation in Ruby.

like image 949
bragboy Avatar asked Sep 08 '26 09:09

bragboy


2 Answers

class MySimpleStructure
  attr_accessor :data1, :data2, :m1
end

s1 = MySimpleStructure.new
s1.data1 = 19
s1.m1 = MyOtherDataStructure.new
like image 197
jigfox Avatar answered Sep 09 '26 22:09

jigfox


In most Ruby code, the hash is used as simple data structures. It's not as efficient as something like this, and there are no definitions of the fields in these hashes, but they're passed around much like a struct in C or simple classes like this in Java. You can of course just do your own class like this:

class MyStruct
  attr_accessor :something, :something_else
end

But Ruby also has a Struct class that can be used. You don't see it much though.

#!/usr/bin/env ruby

Customer = Struct.new('Customer', :name, :email)

c = Customer.new
c.name = 'David Lightman'
c.email = '[email protected]'

There's also OpenStruct.

#!/usr/bin/env ruby
require 'ostruct'

c = OpenStruct.new
c.name = 'David Lightman'
c.greeting = 'How about a nice game of chess?'

I've written about these things here.

like image 33
AboutRuby Avatar answered Sep 09 '26 23:09

AboutRuby