33
34

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.

連続する値を配列に代入したいとき

Posted at

配列に連続する値を代入したいときがあると思います。
例えば"a"〜"c"までの文字が格納されている配列です。
このとき1つずつ値を格納すると下のようになります。

array1.rb
array = ["a", "b", "c"]
p array
# >> ["a", "b", "c"]

しかし"a"〜"z"のように要素が多いと手入力するのが非常にめんどくさいです。
そこで次のようにRangeを使用すると簡単に代入できます。

array2.rb
array = [*("a".."c")]
p array
# >> ["a", "b", "c"]

数値にも使えるので便利です。
下のコードは1〜5の数値を用意し、奇数を取り除きます。

array3.rb
nums = [*(1..5)]                # => [1, 2, 3, 4, 5]
odds = nums.reject { |num| num.odd? }
p odds

# >> [2, 4]
33
34
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
33
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?