当前位置: 移动技术网 > IT编程>脚本编程>Ruby > Ruby中一些基本语法知识点的罗列汇总

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

2017年12月08日  | 移动技术网IT编程  | 我要评论

 让我们写一个简单的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


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网