2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

2
Last updated at Posted at 2016-05-05

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

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"]
2
1
2

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?