3

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.

2 Answers 2

7
class MySimpleStructure attr_accessor :data1, :data2, :m1 end s1 = MySimpleStructure.new s1.data1 = 19 s1.m1 = MyOtherDataStructure.new 
Sign up to request clarification or add additional context in comments.

2 Comments

Why are data1 and data2 symbols but not m1?
sorry, that was a typo
5

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.