【发布时间】:2011-07-29 17:32:43
【问题描述】:
我来自 php,
在 php 中我过度使用了.= 那么,在 ruby 中该怎么做呢?
【问题讨论】:
-
PHP 中没有
=.运算符,只有.=。 -
我确信有很多方法可以产生与使用
=.时 PHP 的“解析错误:语法错误”相当的结果。
我来自 php,
在 php 中我过度使用了.= 那么,在 ruby 中该怎么做呢?
【问题讨论】:
=. 运算符,只有.=。
=. 时 PHP 的“解析错误:语法错误”相当的结果。
String concatentation 在 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"
@AboutRuby 还提到了<< 运算符:
irb(main):001:0> s = "hello"
=> "hello"
irb(main):002:0> s << " world"
=> "hello world"
irb(main):003:0> s
=> "hello world"
虽然他关于+ 创建一个新字符串并且<< 修改一个字符串的观点可能看起来很小,但当您可能对字符串对象有多个引用时,或者如果您的字符串增长为通过重复附加巨大:
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"]
@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"
.join() 方法可以让您免于编写一些糟糕的循环。 :)
【讨论】:
<< 运算符通常优于 +=。 += 创建另一个 String 对象,<< 附加到字符串而不创建另一个对象。
这是用于字符串连接吗?您在 ruby 中使用 += 来连接字符串。
【讨论】:
使用+=。或.concat("string to add")
【讨论】: