我有来自 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
有什么想法或想法吗?谢谢。