代码之家  ›  专栏  ›  技术社区  ›  bragboy

等效于爪哇的Ruby中的简单数据结构

  •  3
  • bragboy  · 技术社区  · 15 年前

    在Java中,如果我想要一个简单的数据结构,我会在一个类似的类中声明它。

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

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

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

    如何在Ruby中执行等效的实现。

    2 回复  |  直到 11 年前
        1
  •  7
  •   jigfox    11 年前
    class MySimpleStructure
      attr_accessor :data1, :data2, :m1
    end
    
    s1 = MySimpleStructure.new
    s1.data1 = 19
    s1.m1 = MyOtherDataStructure.new
    
        2
  •  5
  •   AboutRuby    15 年前

    在大多数Ruby代码中,哈希用作简单的数据结构。它不像这样的东西那么高效,而且这些散列中没有字段的定义,但是它们像C中的结构或Java中的简单类一样传递。当然,你可以这样做你自己的班级:

    class MyStruct
      attr_accessor :something, :something_else
    end
    

    但是Ruby也有一个可以使用的结构类。但你看不太清楚。

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

    我写过这些东西 here .