即时通讯来自php,在php中我过度使用.=,红宝石怎么办?
字符串连接+在Ruby中完成:
$ irb
irb(main):001:0> "hello" + " " + "world"
=> "hello world"
irb(main):002:0> foo = "hello "
=> "hello "
irb(main):003:0> foo += "world"
=> "hello world"
Run Code Online (Sandbox Code Playgroud)
@AboutRuby还提到了<<运营商:
irb(main):001:0> s = "hello"
=> "hello"
irb(main):002:0> s << " world"
=> "hello world"
irb(main):003:0> s
=> "hello world"
Run Code Online (Sandbox Code Playgroud)
虽然他+创建一个新字符串并<<修改字符串的观点可能看起来很小,但是当你对字符串对象有多个引用时,或者如果你的字符串通过重复追加变得很大,那么它很重要:
irb(main):004:0> my_list = [s, s]
=> ["hello world", "hello world"]
irb(main):005:0> s << "; goodbye, world"
=> "hello world; goodbye, world"
irb(main):006:0> my_list
=> ["hello world; goodbye, world", "hello world; goodbye, world"]
irb(main):007:0> t = "hello, world"
=> "hello, world"
irb(main):008:0> my_list = [t, t]
=> ["hello, world", "hello, world"]
irb(main):009:0> t += "; goodbye, world"
=> "hello, world; goodbye, world"
irb(main):010:0> my_list
=> ["hello, world", "hello, world"]
Run Code Online (Sandbox Code Playgroud)
@AboutRuby提到他可以想到三种字符串连接机制; 这让我想起了另一种机制,当你有一个你希望连接在一起的字符串数组时更合适:
irb(main):015:0> books = ["war and peace", "crime and punishment", "brothers karamozov"]
=> ["war and peace", "crime and punishment", "brothers karamozov"]
irb(main):016:0> books.join("; ")
=> "war and peace; crime and punishment; brothers karamozov"
Run Code Online (Sandbox Code Playgroud)
该.join()方法可以避免编写一些可怕的循环.:)
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |