【问题标题】:ruby on rails string concationation like the php (.=)ruby on rails string concationation 像 php (.=)
【发布时间】:2011-07-29 17:32:43
【问题描述】:

我来自 php, 在 php 中我过度使用了.= 那么,在 ruby​​ 中该怎么做呢?

【问题讨论】:

  • PHP 中没有=. 运算符,只有.=
  • 我确信有很多方法可以产生与使用 =. 时 PHP 的“解析错误:语法错误”相当的结果。

标签: php ruby


【解决方案1】:

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"

虽然他关于+ 创建一个新字符串并且&lt;&lt; 修改一个字符串的观点可能看起来很小,但当您可能对字符串对象有多个引用时,或者如果您的字符串增长为通过重复附加巨大:

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() 方法可以让您免于编写一些糟糕的循环。 :)

【讨论】:

  • &lt;&lt; 运算符通常优于 +=+= 创建另一个 String 对象,&lt;&lt; 附加到字符串而不创建另一个对象。
  • @AboutRuby,好点;添加的示例。我建议在这里也添加一个答案,以便对其进行投票。 :)
【解决方案2】:

这是用于字符串连接吗?您在 ruby​​ 中使用 += 来连接字符串。

【讨论】:

    【解决方案3】:

    使用+=。或.concat("string to add")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 2016-04-25
      • 2018-10-27
      • 1970-01-01
      相关资源
      最近更新 更多