开发者

Simple data structure in Ruby equivalent to Java

开发者 https://www.devze.com 2023-01-12 09:07 出处:网络
In Java if I want a simple data structure I would simply declare it in a class something like this class MySimpleStructure{

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

class MySimpleStructure{
   int data1;
开发者_Python百科   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.


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

s1 = MySimpleStructure.new
s1.data1 = 19
s1.m1 = MyOtherDataStructure.new


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 = 'pwned@wopr.mil'

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消