简体   繁体   中英

ruby on rails string concationation like the php (.=)

即时通讯来自php,在php中我过度使用.=所以,红宝石怎么办?

String concatentation is done with + in 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 also mentions the << operator:

irb(main):001:0> s = "hello"
=> "hello"
irb(main):002:0> s << " world"
=> "hello world"
irb(main):003:0> s
=> "hello world"

While his point that + creates a new string and << modifies a string might seem like a small point, it matters a lot when you might have multiple references to your string object, or if your strings grow to be huge via repeated appending:

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 mentioned he could think of three mechanisms for string concatenation; that reminded me of another mechanism, which is more appropriate when you've got an array of strings that you wish to join together:

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"

The .join() method can save you from writing some awful loops. :)

Use += . or .concat("string to add")

Is that for string concatenation? You use += in ruby to concat string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM