让无涯教程用Ruby编写一个简单的程序,所有的ruby文件都将具有扩展名 .rb 。因此,将以下源代码放入test.rb文件中。
#!/usr/bin/ruby -w puts "Hello, Ruby!";
在这里,假设您在/usr/bin目录中有Ruby解释器,现在,尝试按以下方式运行此程序-
$ruby test.rb
这将产生以下输出-
Hello, 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标识符区分大小写。这意味着Ram和RAM是Ruby中的两个不同的标识符。
Ruby标识符名称可以包含字母数字字符和下划线字符(_)。
以下列表显示了Ruby中的保留字。这些保留字不能用作常量或变量名。但是,它们可以用作方法名称。
BEGIN | do | next | then |
END | else | nil | true |
alias | elsif | not | undef |
and | end | or | unless |
begin | ensure | redo | until |
break | false | rescue | when |
case | for | retry | while |
class | if | return | while |
def | in | self | __ FILE __ |
defined | module | super | __ LINE __ |
"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.
BEGIN { code }
声明代码在程序运行之前被调用。
#!/usr/bin/ruby puts "This is main Ruby Program" BEGIN { puts "Initializing Ruby Program" }
这将产生以下输出-
Initializing Ruby Program This is main Ruby Program
END { code }
声明要在程序结尾处调用的 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解释器中隐藏了一行,一行的一部分或几行。您可以在行的开头使用井号(#)-
# 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中的常量。在编程中,习惯上以大写形式写入常量的所有字符。
#!/usr/bin/ruby Name = "Robert" AGE = 23 Name = "Juliet"
在上面的示例中,创建了两个常量。常量之一将在以后重新定义。
Name = "Robert" AGE = 23
创建两个常量。当标识符的名称以大写字母开头时,在Ruby中将有一个常量。按照约定,常量通常用大写字母表示。
Name = "Juliet"
无涯教程重新定义一个常数。哪个发出警告。
$ ./constants.rb ./constants.rb:6: warning: already initialized constant Name ./constants.rb:3: warning: previous definition of Name was here
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)