开发者

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

开发者 https://www.devze.com 2023-02-21 22:08 出处:网络
im from php, in php i overly 开发者_运维知识库use .= so, how do it in ruby?String concatentation is done with + in Ruby:

im from php, in php i overly 开发者_运维知识库use .= so, how do it in ruby?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消