常用ice数据结构在ruby中的表现方式

本文介绍如何将用户自定义类型如枚举、结构体、序列等映射到Ruby语言中。通过示例展示了不同类型的转换过程及使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=large]Mapping for User-Defined Types[/size]


Mapping for Enumerations

enum Fruit { Apple, Pear, Orange };
The generated Ruby class looks as follows:
class Fruit
include Comparable
Apple = # ...
Pear = # ...
Orange = # ...
def Fruit.from_int(val)
def to_i
def to_s
def <=>(other)
def hash
# ...
end

Given the above definitions, we can use enumerated values as follows:
f1 = Fruit::Apple
f2 = Fruit::Orange

枚举类型变成了ruby的类,通过类方法访问枚举的属性


Mapping for Structures

struct Employee {
long number;
string firstName;
string lastName;
};
The Ruby mapping generates the following definition for this structure:
class Employee
def initialize(number=0, firstName='', lastName='')
@number = number
@firstName = firstName
@lastName = lastName
end
def hash
# ...
end
def ==
# ...
end
def inspect
# ...
end
attr_accessor :number, :firstName, :lastName
end

结构体变成了ruby的类,通过实例方法访问结构体的属性


Mapping for Sequences

sequence<Fruit> FruitPlatter;
We can use the FruitPlatter sequence as shown below:
platter = [ Fruit::Apple, Fruit::Pear ]
platter.push(Fruit::Orange)

Fruit序列变成了ruby中的数组,元素的class是Fruit


Mapping for Dictionaries

dictionary<long, Employee> EmployeeMap;
As for sequences, the Ruby mapping does not create a separate named type for
this definition. Instead, all dictionaries are simply instances of Ruby’s hash
collection type. For example:
em = {}
e = Employee.new
e.number = 31
e.firstName = "James"
e.lastName = "Gosling"
em[e.number] = e

dictionary怎么翻译,字典?呵呵。反正对应ruby是hash。


Mapping for Constants

const bool AppendByDefault = true;
const byte LowerNibble = 0x0f;
const string Advice = "Don't Panic!";
const short TheAnswer = 42;
const double PI = 3.1416;
enum Fruit { Apple, Pear, Orange };
const Fruit FavoriteFruit = Pear;
The generated definitions for these constants are shown below:
AppendByDefault = true
LowerNibble = 15
Advice = "Don't Panic!"
TheAnswer = 42
PI = 3.1416
FavoriteFruit = Fruit::Pear

很容易理解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值