LoginSignup
3
1

More than 5 years have passed since last update.

rubyの文字列連結(<<と+)の違い

Last updated at Posted at 2016-11-06

みなさん、以下の結果について、予想できますか?
筆者はこれにハマってしまいました

string = ''
hashes = []
%w(a b c).each do |word|
    string << word
    hashes.push(string: string)
end

p hashes

筆者は以下のような出力を考えていました。。。

hashes = [
    {string: "a"},
    {string: "ab"},
    {string: "abc"}
]

しかし、実際には以下の出力となります。

hashes = [
    {string: "abc"},
    {string: "abc"},
    {string: "abc"}
]

これを想定通りの出力にするならこうです。

string = ''
hashes = []
%w("a b c").each do |word|
    string +=  word
    hashes.push(string: string)
end

p hashes

ポイントは文字列連結で、 << ではなく + を使っている部分ですが、<<では同一のオブジェクトに対して中身を書き換えているのに対して、+では別のオブジェクトを生成するためです。(Javaの文字列連結みたいなものですね)

3
1
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1