簡體   English   中英

Ruby中的簡單數據結構等同於Java

[英]Simple data structure in Ruby equivalent to Java

在Java中,如果我想要一個簡單的數據結構,我只需在類中聲明它

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

然后我會在我的程序中使用它,

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

如何在Ruby中進行等效實現。

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

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

在大多數Ruby代碼中,哈希用作簡單的數據結構。 它不像這樣的效率,並且這些哈希中沒有字段的定義,但是它們很像C中的結構或Java中的簡單類。 你當然可以像這樣做自己的課:

class MyStruct
  attr_accessor :something, :something_else
end

但Ruby也有一個可以使用的Struct類。 你看不太多。

#!/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?'

我在這里寫過這些東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM