手机
当前位置:查字典教程网 >脚本专栏 >ruby专题 >Ruby中一些基本语法知识点的罗列汇总
Ruby中一些基本语法知识点的罗列汇总
摘要:让我们写一个简单的ruby程序。所有Ruby源文件将以扩展名.rb。因此,把下面的源代码在一个test.rb文件。#!/usr/bin/ru...

让我们写一个简单的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的中的保留字。这些保留字不能用作常数或变量名。然而,它们可以被用作方法名。

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

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

【Ruby中一些基本语法知识点的罗列汇总】相关文章:

Ruby基础知识之数据类型

ruby 一些简单的例子

在Ruby中处理日期和时间的教程

对优化Ruby on Rails性能的一些办法的探究

Ruby中相等性判断的4种方法

Ruby中实现把字符串转换为类的2种方法

Ruby中任务构建工具rake的入门学习教程

用Ruby进行CGI编程的入门指引

详解Ruby中的单件方法和单件类

详解Ruby中范围的概念

精品推荐
分类导航