Simple Ruby equivalent Java data structure

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

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

Then I later used it in my program,

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

How to do an equivalent implementation in Ruby.

+3
source share
2 answers
class MySimpleStructure
  attr_accessor :data1, :data2, :m1
end

s1 = MySimpleStructure.new
s1.data1 = 19
s1.m1 = MyOtherDataStructure.new
+7
source

Most Ruby code uses a hash as a simple data structure. It's not as efficient as something like that, and there are no field definitions in these hashes, but they are passed in the same way as a structure in C or simple classes like this in Java. You can, of course, just make your own class as follows:

class MyStruct
  attr_accessor :something, :something_else
end

But Ruby also has a Struct class that you can use. You do not see this much, though.

#!/usr/bin/env ruby

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

c = Customer.new
c.name = 'David Lightman'
c.email = 'pwned@wopr.mil'

OpenStruct.

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

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

.

+5

Source: https://habr.com/ru/post/1760974/


All Articles