去年的时候,Ruby on Rails(RoR)Web框架使Ruby有了更进一步的发展。RoR结构利用简单的Ruby代码定义了一个典型的多层次Web应用程序——图形页面层、业务逻辑层和数据持久层,因此减小了冗余文件、样本文件代码、生成的源代码以及配置文件。RoR框架能够更加优化更加容易地使用Ruby语言;而且 Ruby,这种完善的脚本语言,相对于RoR框架来说可以在更多的领域里面使用。
class ADuck
def quack()
puts "quack A";
end
end
class BDuck
def quack()
puts "quack B";
end
end
# quack_it doesn't care about the type of the argument duck, as long
# as it has a method called quack. Classes A and B have no
# inheritance relationship.
def quack_it(duck)
duck.quack
end
a = ADuck.new
b = BDuck.new
quack_it(a)
quack_it(b)
更有趣的是,对于Java程序员寻找的新的和有用的观点,Ruby支持功能范例。你可以在Java里面使用更多的功能程序结构,使用很多类库支持就像 Jakarta Commons Collections系列的集合包一样,但是这些语法是笨拙的。Ruby,虽然不是一种纯功能性语言,但是对待功能和匿名块如同完整的语言成员一样,这些都是能够像其他简单对象一样被传递到周围和利用的。
Listing 3. Add method to built-in classes String and Fixnum
代码:
class String
# Returns true if string is all white space.
# The question mark indicates a Boolean return value.
def blank?()
!(self = /\S/)
end
endclass Fixnum
# Returns 0 or 1 which in Ruby are treated as false and true respectively.
def odd?()
return self % 2
end
endputs " ".blank? # true
# The next line evaluates if-then similarly to Java's ternary operator ?:
puts (if 23.odd? then "23 odd" else "23 even" end)