Ruby中一些基本语法知识点的罗列汇总

 让我们写一个简单的ruby程序。所有Ruby源文件将以扩展名.rb。因此,把下面的源代码在一个test.rb文件。

#!/usr/bin/ruby -w

puts "Hello, Ruby!";

在这里,假定您已经安装有Ruby解释器,可以在/usr/bin目录找到。现在尝试运行此程序如下:

$ ruby test.rb

这将产生以下结果:

Hello, Ruby!

通过以上实例,我们已经看到了一个简单的Ruby程序,现在让我们来看看有关Ruby语法的几个基本概念:
Ruby程序中的空白符:

在Ruby代码一般都忽略空白字符,例如空格和制表符,除非当它们出现在字符串中。但是,有时它们被使用解释模棱两可的报表。诠释这种类型-w选项启用时产生警告。

实例:

a + b is interpreted as a+b ( Here a is a local variable)
a +b is interpreted as a(+b) ( Here a is a method call)

Ruby程序行结尾:

Ruby解释一个语句中以分号和换行符表示结束。但是,如果Ruby遇到运算符,如+,- 或反斜杠结尾的行,则表示语句继续。
Ruby标识符:

标识符是变量,常量及方法。 Ruby的标识符是区分大小写的。Ram和RAM在Ruby中是两个不同意思的标识符。

Ruby的标识符名称可以由字母数字字符和下划线( _ ).
保留字:

下面的列表显示了Ruby的中的保留字。这些保留字不能用作常数或变量名。然而,它们可以被用作方法名。

2015511160750460.jpg (587×347)

 Ruby中heredoc:

"Here Document" 是指建立多行字符串。继<<可以指定一个字符串或者一个标识符来终止字符串字面,当前行之后的所有行的终止符字符串的值。

如果终止符是引用,引号的类型决定面向行的字符串常量的类型。注意<<终止符之间不能有空格。

下面是不同的例子:

#!/usr/bin/ruby -w

print <<EOF
  This is the first way of creating
  here document ie. multiple line string.
EOF

print <<"EOF";        # same as above
  This is the second way of creating
  here document ie. multiple line string.
EOF

print <<`EOC`         # execute commands
 echo hi there
 echo lo there
EOC

print <<"foo", <<"bar" # you can stack them
 I said foo.
foo
 I said bar.
bar

这将产生以下结果:

  This is the first way of creating
  her document ie. multiple line string.
  This is the second way of creating
  her document ie. multiple line string.
hi there
lo there
    I said foo.
    I said bar.

Ruby BEGIN 语句
语法:

BEGIN {
  code
}

声明代码在程序运行之前被调用。
例子:

#!/usr/bin/ruby

puts "This is main Ruby Program"

BEGIN {
  puts "Initializing Ruby Program"
}

这将产生以下结果:

Initializing Ruby Program
This is main Ruby Program

Ruby END 语句
语法:

END {
  code
}

声明代码被称为程序的结束。
语法:

#!/usr/bin/ruby

puts "This is main Ruby Program"

END {
  puts "Terminating Ruby Program"
}
BEGIN {
  puts "Initializing Ruby Program"
}

这将产生以下结果:

Initializing Ruby Program
This is main Ruby Program
Terminating Ruby Program

Ruby 注释:

注释隐藏一行,某一行的一部分或几行Ruby解释器忽略解释程序代码。可以使用的的哈希字符(#)开头的一行:

# I am a comment. Just ignore me.

或者,注释可能是在同一行后一个语句或表达式:

name = "Madisetti" # This is again comment

可以注释掉多行如下:

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

这里是另一种形式。此块注释隐藏几行注释: =begin/=end:

=begin
This is a comment.
This is a comment, too.
This is a comment, too.
I said that already.
=end