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标识符

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

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

保留字

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

开始 做 下一个 然后
结尾 别的 零 真的
别名 埃尔西夫 不是 未定义
和 结尾 或者 除非
开始 确保 重做 直到
休息 错误的 救援 什么时候
案件 为了 重试 尽管
班级 如果 返回 尽管
定义 在 自己 __文件__
定义? 模块 极好的 __线__

这里的 Ruby 文档

“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