我有一個Java類下面的代碼:你將如何在Ruby中實現這個Java枚舉類?
enum TokenType {
CHR("[a-z]"),
INTEGER("[0-9]"),
OP_EQUALS("\\="),
OP_PLUS ("\\+"),
OP_MINUS("\\-"),
OP_MULTIPLY("\\*"),
OP_DIVIDE("\\/"),
OP_LESS("\\<"),
LOGIC_AND("and"),
LOGIC_NOT("not"),
LOGIC_TRUE("true"),
LOGIC_FALSE("false"),
PUNCT_LEFTPAREN("\\("),
PUNCT_RIGHTPAREN("\\)"),
PUNCT_SEMIC("\\;"),
EOF("\\#"),
;
private TokenType(String ch) {
this.tokenClass = ch;
}
String tokenClass;
public static TokenType parse(String in) {
for (TokenType type : TokenType.values()) {
if (in.matches(type.tokenClass)) {
return type;
}
}
return null;
}
}
作爲Ruby新手,我試圖找出在Ruby來實現這一點。越簡單越好。我在這裏根據一些帖子嘗試了以下內容,但似乎無法完成。我希望該類有一個parse()方法,該方法將輸入字符串與所有枚舉選項相匹配,如果沒有任何模式匹配,則返回null。這是我迄今爲止所嘗試的:
class TokenType
attr_accessor :tokenClass
def initialize(str)
@tokenClass = str
end
CHR = new("[a-z]")
INTEGER = new("[0-9]"),
OP_EQUALS = new("\\="),
OP_PLUS = new("\\+"),
OP_MINUS= new("\\-"),
OP_MULTIPLY= new("\\*"),
OP_DIVIDE = new("\\/"),
OP_LESS = new("\\<"),
LOGIC_AND = new("and"),
LOGIC_NOT = new("not"),
LOGIC_TRUE = new("true"),
LOGIC_FALSE = new("false"),
PUNCT_LEFTPAREN = new("\\("),
PUNCT_RIGHTPAREN = new("\\)"),
PUNCT_SEMIC = new("\\;"),
EOF= new("\\#"),
class << self
private :new
end
def TokenType.parse(str_in)
end
end
任何想法或想法?謝謝。
您可以從閱讀此前的文章開始:http://stackoverflow.com/questions/75759/enums-in-ruby – fmendez
感謝您的參考,但我已經看過那個線程,仍然只能夠得到至於我上面的Ruby代碼。 – runit