8.2 再说字符串

一. 生成一个字符串
字符串是String类的对象,一般使用字面值来创建。

ruby 代码
  1. #E8.2-1.rb   
  2.   
  3. str1 = 'this is str1'   
  4. str2 = "this is str2"  
  5. str3 = %q/this is str3/   
  6. str4 = %Q/this is str4/   
  7. str5 =《EOF_STRING<ok_str span=""></ok_str> 
  8.   Here is string document, str5   
  9.      line one;   
  10.      line two;   
  11.      line three.   
  12.   OK   
  13. EOF_STRING<ok_str span=""></ok_str> 
  14.   
  15. puts str3   
  16. puts str4   
  17. puts str5   
  18.   


运行结果:
>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类的方法非常多,下面略举几例。

ruby 代码
  1. #E8.2-2.rb   
  2.   
  3. str = ' this' + " is"  
  4. str += " you"  
  5. str << " string" << " ."  
  6.   
  7. puts  str*2       # =>  this is you string . this is you string .   
  8. puts  str[-12,12]  # => you string .  



三. 字符串转义
双引号括起来的字符串会有转义,例如:“\n” 表示换行。还有一些其它的转义符号,比如制表符之类。

ruby 代码
  1. #E8.2-3.rb   
  2.   
  3. str = " this is you string ."  
  4. puts  str*2                     # =>  this is you string . this is you string .   
  5.   
  6. str = " this is you string .\n"  
  7. puts  str*2                     # =>  this is you string .   
  8.                                   this is you string .   
  9. str = " \tthis is you string ."  
  10. puts  str                       # =>   this is you string .   
  11.   
  12. str = ' this\'s you string .\n'   
  13. puts  str                       # =>  this's you string .\n  


单引号括起来的字符串并不会对字符串作任何解释,你看到的是什么便是什么,有一个例外:单引号字符串里的 单引号 需要转义。

四. 字符串内嵌表达式
在双引号扩起来的字符串中,不仅可以使用各种转义符,而且可以放置任意的Ruby表达式在 #{   } 之中,这些表达式在使用这个字符串的时候被计算出值,然后放入字符串。

ruby 代码
  1. #E8.2-4.rb   
  2.   
  3. def hello(name)   
  4.     " Welcome, #{name} !"  
  5. end  
  6.   
  7. puts  hello("kaichuan")   # =>  Welcome, kaichuan !   
  8. puts  hello("Ben")       # =>  Welcome, Ben !  


字符串内嵌表达式,使得你能够更加灵活地组织代码,表现出更强、更多的动态特性。

完整阅读,请看我写的 Ruby语言中文教程all in one    
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值