Ruby


Ruby (正體)

Free Web Hosting with Website Builder
Ruby
multi-paradigm
面市時間
1995年
设计者
松本行弘
实作者
松本行弘(和其他许多人)
最近释出日期 1.9.0/ 2007年12月25日
dynamic ("duck")
主要实作产品
Ruby, JRuby
启发语言
Smalltalk, Perl, Lisp, Python, CLU, Dylan
影响语言
Groovy
跨平台
Ruby License / GPL
www.ruby-lang.org


Ruby,一种为简单快捷面向对象编程面向对象程序设计)而创的脚本语言,由日本人松本行弘(まつもとゆきひろYukihiro Matsumoto,外号 matz)开发,遵守GPL协议和Ruby License

目录

历史

Ruby的作者于1993年2月24日开始编写Ruby,直至1995年12月才正式公开发布于fj(新闻组)。之所以称为Ruby,是因为Perl的发音与6月的诞生石pearl(珍珠)相同,因此Ruby以7月的诞生石ruby(红宝石)命名。

Ruby明显比其他类似的编程语言(如PerlPython)年轻,又因为Ruby是日本人发明的,所以早期的非日文资料和程式都比较贫乏,所以现在在网上仍然可以找到Ruby的资料太少之类的批评。约于2000年,Ruby开始进入美国,英文的资料开始发展。

Ruby 的理念

减少编程时候的不必要的琐碎时间,令编写程序的人高兴,是设计 Ruby 语言的 Matz 的一个首要的考虑;其次是良好的界面设计。他强调系统设计必须强调人性化,而不是一味从机器的角度设想[1]

人们特别是电脑工程师们,常常从机器着想。他们认为:“这样做,机器就能运行的更快;这样做,机器运行效率更高;这样做,机器就会怎样怎样怎样。”实际上,我们需要从人的角度考虑问题,人们怎样编写程序或者怎样使用机器上应用程序。我们是主人,他们是仆人。

遵循上述的理念,Ruby 语言通常非常直观,按照编程人认为它应该的方式运行。

Ruby的作者认为Ruby > (Smalltalk + Perl) / 2[来源请求],表示Ruby是一个语法像Smalltalk一样完全面向对象、脚本执行、又有Perl强大的文字处理功能的编程语言。其他特色包括:

语意

Ruby 是完全面向对象的:任何一点数据都是对象,包括在其他语言中的基本类型(比如:整数,布尔逻辑值),每个过程或函数都是方法。

Ruby 的 Hello World 程序

下面是一个在标准输出设备上输出 Hello World 的简单程序,这种程序通常作为开始学习编程语言时的第一个程序:

#!/usr/bin/env ruby
puts "Hello, world!"

或者是在 irb 交互式命令列的模式下:

>>puts "Hello, world!"
Hello, world!
=> nil

程式范例

下面的代码可以在 Ruby shell 中运行,比如 irb 交互式命令列,或者保存为文件并运行命令 ruby <filename>

  • 一些基本的 Ruby 代码:
# Everything, including a literal, is an object, so this works:
-199.abs                                                # 199
"ruby is cool".length                                   # 12
"Rick Astley".index("c")                                # 2
"Nice Day Isn't It?".downcase.split(//).sort.uniq.join  # " '?acdeinsty"
  • 一些转换:
puts "What's your favorite number?"
number = gets.chomp
outputnumber = number.to_i + 1
puts outputnumber.to_s + ' is a bigger and better favorite number.'

字符串

在 Ruby 中定义字符串的各种方法

  • 下面的转换同双引号的字符串是等价的:
a = "\nThis is a double quoted string\n"
a = %Q{\nThis is a double quoted string\n}
a = <<BLOCK
  • 这是双引号字符串的多行形式:
BLOCK
a = %/\nThis is a double quoted string\n/
  • 下面的转换同单引号字符串是等价的:
a = 'This is a single quoted string'
a = %q{This is a single quoted string}

集合

a = [1,'hi', 3.14, 1, 2, [4, 5]]
 
p a[2]           # 3.14
p a.[](2)        # 3.14
p a.reverse      # [[4, 5], 2, 1, 3.14, 'hi', 1]
p a.flatten.uniq # [1, 'hi', 3.14, 2, 4, 5]
  • 构造和使用关联数组:
hash = { :water => 'wet', :fire => 'hot' }
puts hash[:fire] # Prints:  hot
 
hash.each_pair do |key, value| # Or:  hash.each do |key, value|
  puts "#{key} is #{value}"
end
 
# Prints:  water is wet
#          fire is hot
 
hash.delete :water # Deletes :water => 'wet'
hash.delete_if {|k,value| value=='hot'} # Deletes :fire => 'hot'

块和迭代器

  • 有两个语法用于创建块:
{ puts "Hello, World!" } # Note the { braces }
#or
do puts "Hello, World!" end
  • 传参数的块使用闭包Closure
# In an object instance variable (denoted with '@'), remember a block.
def remember(&a_block)
  @block = a_block
end
 
# Invoke the above method, giving it a block which takes a name.
remember {|name| puts "Hello, #{name}!"}
 
# When the time is right (for the object) -- call the closure!
@block.call("Jon")
# => "Hello, Jon!"
  • 从方法中返回闭包:
def create_set_and_get(initial_value=0) # Note the default value of 0
  closure_value = initial_value
  return Proc.new {|x| closure_value = x}, Proc.new { closure_value }
end
 
setter, getter = create_set_and_get  # ie. returns two values
setter.call(21)
getter.call # => 21
  • 迭代调用调用时提供的块:
def use_hello
  yield "hello"
end
 
# Invoke the above method, passing it a block.
use_hello {|string| puts string} # => 'hello'
  • 使用块迭代数组:
array = [1, 'hi', 3.14]
array.each { |item| puts item }
# => 1
# => 'hi'
# => 3.14
 
array.each_index { |index| puts "#{index}: #{array[index]}" }
# => 0: 1
# => 1: 'hi'
# => 2: 3.14
 
(3..6).each { |num| puts num }
# => 3
# => 4
# => 5
# => 6

像 inject() 方法可以接收一个参数和一个块。迭代的注入列表的每一个成员,执行函数时保存总和。这同函数编程语言中的 foldl 函数相类似,比如:

[1,3,5].inject(10) {|sum, element| sum + element} # => 19

首先块接收到了 10(inject 的参数)当作变量 sum,并且 1(数组的第一个元素)当作变量 element;这会返回 11。11 又被当作下一步的 sum 变量,它加上 3 得到了 14。14 又被加上了 5,最终返回结果 19。

  • 块运行在内置的方法中:
File.open('file.txt', 'w') do |file| # 'w' denotes "write mode".
  file.puts 'Wrote some text.'
end                                  # File is automatically closed here
 
File.readlines('file.txt').each do |line|
  puts line
end
# => Wrote some text.
  • 使用枚举器和块求 1 到 10 的平方:
(1..10).collect {|x| x*x} # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

下面的代码定义一个命名为 Person 的类。含有一个“initialize”方法,用于构选创建一个新对象,它还有两个方法,一个重载了 <=> 比较运算符(这样 Array#sort 可以使用 age 排序)另一个重载了 to_s 方法(这样 Kernel#puts 可以格式化输出),attr_reader 是 Ruby 中元数据编程的例子:attr_accessor 为实例变量定义了 getter 和 setter 方法,attr_reader 只是一个 getter 方法。另外,方法中最后的声明是它的返回值,也允许显式的使用“return”语句。

class Person
  attr_reader :name, :age
  def initialize(name, age)
    @name, @age = name, age
  end
  def <=>(person) # Comparison operator for sorting
    @age <=> person.age
  end
  def to_s
    "#@name (#@age)"
  end
end
 
group = [
  Person.new("Bob", 33), 
  Person.new("Chris", 16), 
  Person.new("Ash", 23) 
]
 
puts group.sort.reverse
  • 下面按 age 倒序输出了三个名字:
Bob (33)
Ash (23)
Chris (16)

元数据编程

Ruby 为程序员在运行时期间向标准库加入或修改方法的能力,同样 Ruby 在执行时修改它自身而无需生成代码,这种技术被称为元数据编程。这是一个为标准库的 Time 类添加方法的简单例子:

# re-open Ruby's Time class
class Time
  def yesterday
    self - 86400
  end
end
 
today = Time.now # => Thu Aug 14 16:51:50 +1200 2008
yesterday = today.yesterday # => Wed Aug 13 16:51:50 +1200 2008

Ruby 的特点

完全面向对象

在Ruby语言中,任何东西都是对象,包括其他语言中的基本数据类型,比如整数。

变量没有类型

Ruby的变量可以保有任何类型的数据。

任何东西都有值

不管是数学或者逻辑表达式还是一个语句,都有值。

变量命名规则

Ruby的变量有以下几种:

  • 一般小写字母、底线开头:变量,变量 (Variable)。
  • $开头:全域变量,全局变量 (Global variable)。
  • @开头:实体变量,实例变量 (Instance variable)。
  • @@开头:类别变量,类变量 (Class variable)。
  • 大写字母开头:常数 (Constant)。

已经定义的类可以在运行时修改

Ruby是动态语言,你可以在程序中修改先前定义过的类。 也可以在某个类的实例中定义该实例特有的方法,这叫做单例方法。

class MyClass
  def the_method
    "general method"
  end
end
 
mc = MyClass.new
def mc.the_method
  "special for this instance."
end
 
mc.the_method

JRuby

JRuby,类似PythonJython,一个可于Java上执行Ruby的语言,支援Java的接口和类别。最新发布版为1.1.4(2008-8-28),与Ruby 1.8.6兼容。它的官方网站为jruby.codehaus.org

和 Perl 6 比较

  • CPAN 上排名第一名,同时也是 Perl 6 的开发者的唐凤(Autrijus / Audrey)说:“Ruby 就是‘没有到处打广告的 Perl 6’”。[2]
  • 松本行弘在接受欧莱礼(O'Reilly)访问时,提到“Ruby 借用了很多 Perl 的东西……,Python 远比 Perl 要少……”、“我认为 Ruby 这个名字作为 Perl 之后的一门语言的名字真是再恰当不过了。”[3]
  • Perl 之父拉里·沃尔(Larry Wall)说:“很多方面上我还是很喜欢 Ruby 的,这是因为那些部分是从 Perl 借过去的。:-)”、“我还喜欢 Ruby 的 C<*> 一元星号操作符,所以我把它加到 Perl 6 里面。”[4]

参见

参考文献

外部链结

中文资源







Why are we here?
All text is available under the terms of the GNU Free Documentation License
This page is cache of Wikipedia. History