Ruby - 语法

让我们在ruby中编写一个简单的程序.所有ruby文件都将具有扩展名 .rb .因此,将以下源代码放在test.rb文件中.

#!/usr/bin/ruby -w

puts "Hello, Ruby!";

在这里,我们假设你在/usr/bin目录中有Ruby解释器.现在,尝试运行此程序如下 :

$ 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 Identifiers

标识符是变量,常量和方法的名称. Ruby标识符区分大小写.这意味着Ram和RAM是Ruby中的两个不同标识符.

Ruby标识符名称可能由字母数字字符和下划线字符(_)组成.

保留字

以下列表显示了Ruby中的保留字.这些保留字不能用作常量或变量名.但是,它们可以用作方法名称.

BEGINdonextthen
ENDelseniltrue
aliaselsifnotundef
andendorunless
beginensureredountil
breakfalserescuewhen
caseforretrywhile
classifreturnwhile
definself__FILE__
defined?modulesuper__LINE__


这里的Ruby文档

"Here Document"指的是build来自多行的字符串.在<<<<你可以指定一个字符串或一个标识符来终止字符串文字,当前行到终结符后面的所有行都是字符串的值.

如果引用了终结符,引号类型确定面向行的字符串文字的类型.请注意,<<之间不能有空格.这是不同的例子和减号;

#!/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