我应该如何用Ruby编程

我应该如何用Ruby编程,ruby,Ruby,下面是我要做的:用户输入一个字符串。字符串包含两部分,如下所示: {EventClass: someMethod=>arg1, arg2, arg3....}, {Action: someMethod=>arg1, arg2, arg3....} 这方面的一个具体例子是: {TwitterEvent: newTweet=>arg1, arg2, arg3....}, {PersistenceAction: saveToHardDrive=>arg1 arg2...}

下面是我要做的:用户输入一个字符串。字符串包含两部分,如下所示:

{EventClass: someMethod=>arg1, arg2, arg3....}, {Action: someMethod=>arg1, arg2, arg3....}
这方面的一个具体例子是:

{TwitterEvent: newTweet=>arg1, arg2, arg3....}, {PersistenceAction: saveToHardDrive=>arg1 arg2...}
然后我将解析这个字符串,实例化
TwitterEvent
的一个实例,并对其调用该方法。然后对
PersistenceAction


这类应用的最佳“设计”是什么?如何从解析的字符串动态实例化类,然后调用方法?这个方法可能会有参数?如何检测/处理错误?

从名称字符串获取类对象:

 Kernel.const_get('TwitterEvent')
对对象调用任意方法:

 event.send(:new_tweet)
其余由您决定。:-)

您想要使用。Send允许您使用符号调用方法。可以使用to_sym将字符串转换为符号

给你

str = "{TwitterEvent: newTweet=>arg1, arg2, arg3}, {PersistenceAction: saveToHardDrive=>arg1, arg2}"

regexp = /^{(\w+):\s*(\w+)=>([^}]+)},\s*{(\w+):\s*(\w+)=>([^}]+)}$/

regexp.match(str).to_a[1..-1].each_slice(3) do |s|
  # s[0] .. class name
  # s[1] .. class method
  # s[2] .. method parameters as a single string
  # do something similar to Sergio Tulentsev suggestion
end

使用稍微不同的输入格式会更容易,比如说,合法的散列。