Ruby Programming/Strings

维基教科书,自由的教学读本

← Hello world | Here documents →

Python, Java, 与 .NET Framework一样, Ruby 也有内建字串类别。

String literals[编辑]

建立一个字串可以用单引号或双引号把字包住,可以参考一下"hello world"这个范例。 这个范例程式码示范了用单引号跟双引号包住字串的两种方法。

puts 'Hello world'
puts "Hello world"

Being able to use either single or double quotes is similar to Perl, but different from languages such as C and Java, which use double quotes for string literals and single quotes for single characters.

那么单引号跟双引号在Ruby中有什么不一样的呢?在上面的程式码中并没有不同,然而看看底下的程式码吧:

puts "Betty's pie shop"
puts 'Betty\'s pie shop'

Because "Betty's" contains an apostrophe, which is the same character as the single quote, in the second line we need to use a backslash to escape the apostrophe so that Ruby understands that the apostrophe is in the string literal instead of marking the end of the string literal. The backslash followed by the single quote is called an escape sequence.

单引号[编辑]

单引号只允许两个跳脱字元

  • \' – 单引号
  • \\ – 单斜线

双引号[编辑]

双引号允许了比单引号更多的跳脱字元。他也允许你嵌入变数或者Ruby程式码在一个字串内

跳脱字元[编辑]

下面是一些在双引号内常用的跳脱字元:

试试看这些范例,可以帮助你更加了解跳脱字元的用处:

puts "Hello\t\tworld"

puts "Hello\b\b\b\b\bGoodbye world"

puts "Hello\rStart over world"

puts "1. Hello\n2. World"

执行结果:

$ double-quotes.rb
Hello		world
Goodbye world
Start over world
1. Hello
2. World

注意换行的跳脱字元很单纯的就是换新的一行。

\a可以产生警示音,这是一个控制字元。It does not represent a letter of the alphabet, a punctuation mark, or any other written symbol. Instead, it instructs the terminal emulator (called a console on Microsoft Windows) to "alert" the user. It is up to the terminal emulator to determine the specifics of how to respond, although a beep is fairly standard. Some terminal emulators will flash briefly.

执行底下的Ruby程式码可以知道警示音是什么:

puts "\aHello world\a"

puts[编辑]

我们已经使用过puts函式印出一些文字。在任何时候puts可以输出文字到萤幕上,然后自动再最后面替你换上一行,举例来说:

puts "Say", "hello", "to", "the", "world"

执行结果

$ hello-world.rb
Say
hello
to
the
world

print[编辑]

对照之后,Ruby的print函式只会在你要求换行时才会输出换行字元。举例来说:

print "Say", "hello", "to", "the", "world", "\n"

执行结果

$ hello-world.rb
Sayhellototheworld

底下的程式码跟全部写在同一行会有相同的执行结果

print "Say"
print "hello"
print "to"
print "the"
print "world"
print "\n"