First glance at Ruby
大年三十的时候,上班已经没什么事儿了,就仔细读了读以前保存的很多不错的文章,包括这一篇"Ruby, PHP and a Conference",作者是大名鼎鼎的Bruce Eckle,"Thinking in Java"这个经典教材的作者。
一直就很想看看Ruby这个很火的语言,这两天终于有些时间,就找了一些文章看了看。
强烈推荐一篇"10 Things Every Java Programmer Should Know About Ruby",挺不错。
总结一下Ruby吸引我的地方:
1) Case Statement
In Ruby, the case statement can match with any object. It uses the “===” method in Object to perform the match, which can be overridden for your own classes. Since everything is really an object in Ruby, this includes any type of literal, regular expressions, and object types.
2) Easy Reflection
Eclipse Plugin Framework中,实例化一个插件类的代码是:
- try {
- // 用每个插件自己的PluginClassLoader来得到这个插件的主类
- pluginClass = descr.getPluginClassLoader().loadClass(
- className);
- } catch (ClassNotFoundException cnfe) {
- badPlugins_.add(descr.getId());
- throw new PluginException("can't find plug-in class " + className);
- }
- try {
- Class pluginManagerClass = getClass();
- Class pluginDescriptorClass = IPluginDescriptor.class;
- Constructor constructor = pluginClass
- .getConstructor(new Class[] { pluginManagerClass,
- pluginDescriptorClass });
- // 调用插件默认的构造函数
- // Plugin(PluginManager, IPluginDescriptor);
- result = (Plugin) constructor.newInstance(new Object[] {
- this, descr });
- } catch (InvocationTargetException ite) {
- ... ...
- } catch (Exception e) {
- ... ...
- }
在Ruby中,Reflection变的异常简单:
- def create(klass, value)
- klass.new(value)
- end
- g = create(Greeting, "Hello")
3) Everything is Message
任何函数调用都是消息,object.test(arg1)就是像object发送test消息,参数为arg1。这样带来的好处是,这多一层的抽象性,可以让你有更多的控制权。
比如:
- Remote Proxies
- Automatically forward any message to a remote object.
- Auto Loaders
- Stand in for an object until it gets its first message. Then load it and act like a regular proxy. Great for autoloading database backed objects.
- Decorators
- Intercept the messages you want and pass the rest through.
- Mock Objects
- Just write the methods that need to be mocked. Proxy or ignore the others as needed.
- Builders
- Generate XML/HTML/Whatever based on the methods called on the builder
4) Block
大米曾经讲过一次Block,我还是觉得Block就是Command模式的应用,当然,yield已经是嵌入到Ruby语言中的关键字了。
5) Open Classes
这算是一个很酷的Feature,谁都可以扩展类的定义,既可以扩展整个类,也可以扩展某个实例,Cool。
扩展类定义 (例子是扩展系统自定义的Array类)
- class Array
- def dump
- for x in self
- puts x
- end
- end
- end
- a = [1,2,3,4,5]
- a.dump
扩展类实例 - Singleton Class
- class X
- def f()
- puts "f()!"
- end
- end
- x = X.new
- x.f()
- def x.g()
- puts "g()!"
- end
- x.g()
- y = X.new
- y.f()
- # y.g() # Undefined method
Hooks
在你感兴趣的任何地方添加钩子。
其它还有很多,比如:
- Everything is object
- Implied self argument
- Module & Mix-ins
- … …
Popularity: 24%
Related entries:

March 1st, 2006 at 9:21 pm
def create(klass, value)
klass.new(value)
end
g = create(Greeting, “Hello”)
加强版的define?
March 1st, 2006 at 9:22 pm
我是说C语言的#define
#define create(klass, value)\
klass.new(value);
g = create(Greeting, “Hello”)
March 1st, 2006 at 10:43 pm
这里的重点应该是 klass.new