Help us understand the problem. What is going on with this article?

Rubyで指定した要素の繰り返しで配列を作る方法。

More than 3 years have passed since last update.

以下のようにすれば、指定した文字の繰り返しで配列が作成できる。

sample.rb
array = Array.new(10){"a"}

array[3].upcase!
p array 
#=> ["a", "a", "a", "A", "a", "a", "a", "a", "a", "a"]

なお、Array.newを使わないで以下のようにすると配列はできるが、要素は全て同じオブジェクトになってしまう。そのため要素に破壊的変更を加えると、全ての要素が同じ影響を受けてしまう。

特に理由がなければ上記のやり方のほうがいい。

sample.rb
array = ["a"]*10
# => ["a", "a", "a", "a", "a", "a", "a", "a", "a", "a"]

array[3].upcase!
p array 
=> ["A", "A", "A", "A", "A", "A", "A", "A", "A", "A"]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away