一. 生成一个字符串
字符串是String类的对象,一般使用字面值来创建。
- #E8.2-1.rb
- str1 = 'this is str1'
- str2 = "this is str2"
- str3 = %q/this is str3/
- str4 = %Q/this is str4/
- str5 =《EOF_STRING<ok_str span=""></ok_str>
- Here is string document, str5
- line one;
- line two;
- line three.
- OK
- EOF_STRING<ok_str span=""></ok_str>
- puts str3
- puts str4
- puts str5
运行结果:
>ruby E8.2-1.rb
this is str3
this is str4
Here is string document, str5
line one;
line two;
line three.
OK
>Exit code: 0
%q 用来生成单引号字符串;%Q用来生成双引号字符串。%q或者%Q后面跟着的是分隔符,可以是配对的! !; / /; < >; ( ); [ ] ;{ };等等。
str5是一个字符串文档,从 <<和文档结束符的下一行开始,直到遇到一个放置在行首的文档结束符,结束整个字符串文档。
一个数组可以用join 方法转换成字符串,join( ) 内的参数也是一个字符串,用来分隔数组的每个元素,例如:arr.join(", ")。
二. 字符串操作
字符串既然是String类的对象,String类的方法你都可以使用在字符串变量上,String类的方法非常多,下面略举几例。
- #E8.2-2.rb
- str = ' this' + " is"
- str += " you"
- str << " string" << " ."
- puts str*2 # => this is you string . this is you string .
- puts str[-12,12] # => you string .
三. 字符串转义
双引号括起来的字符串会有转义,例如:“\n” 表示换行。还有一些其它的转义符号,比如制表符之类。
- #E8.2-3.rb
- str = " this is you string ."
- puts str*2 # => this is you string . this is you string .
- str = " this is you string .\n"
- puts str*2 # => this is you string .
- this is you string .
- str = " \tthis is you string ."
- puts str # => this is you string .
- str = ' this\'s you string .\n'
- puts str # => this's you string .\n
单引号括起来的字符串并不会对字符串作任何解释,你看到的是什么便是什么,有一个例外:单引号字符串里的 单引号 需要转义。
四. 字符串内嵌表达式
在双引号扩起来的字符串中,不仅可以使用各种转义符,而且可以放置任意的Ruby表达式在 #{ } 之中,这些表达式在使用这个字符串的时候被计算出值,然后放入字符串。
- #E8.2-4.rb
- def hello(name)
- " Welcome, #{name} !"
- end
- puts hello("kaichuan") # => Welcome, kaichuan !
- puts hello("Ben") # => Welcome, Ben !
字符串内嵌表达式,使得你能够更加灵活地组织代码,表现出更强、更多的动态特性。
完整阅读,请看我写的 Ruby语言中文教程all in one