0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ruby 文字列・配列におけるindexアクセス・置換

Posted at

rubyで、文字列と配列両方で同じように利用できるindexアクセス、置換についての整理です。(これって文字列でもできた気がするけど、どうだっけ、、?)と思いドキュメントを見にいくという機会が多かったので、ここで簡単に整理してしまおうというモチベーションです

共通

indexアクセス

# Array
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
pp arr[3] # => 3
pp arr[1..3] # => [1, 2, 3]
# 注: 配列外にアクセスするとnilが返る(エラーにならないので注意)
pp arr[20] # => nil
# マイナスアクセス
pp arr[-2] # => 8
pp arr[-5..-3] # => [5, 6, 7]
# 一部範囲内でもnilになる
pp arr[-100..-3] # => nil 

# String
str1 = '0123456789'
str2 = 'abcdefg'
pp str1[3] # => '3'
pp str2[2] # => 'c'
pp str1[1..3] # => "123"
pp str2[2..5] # => "cdef"
# 注: 同じく範囲外だとnilが返る
pp str1[14] # => nil
# マイナスアクセス
pp str1[-1] # => '9'
pp str1[-3..-1] # => '789'
pp str1[-100..-1] # => nil

置換

# Array
arr1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2 = [111, 222, 333]
arr1[1..3] = arr2
pp arr1 # => [0, 111, 222, 333, 4, 5, 6, 7, 8, 9]
# 注意: 一つの要素を配列で置き換えると、二重配列になる
arr1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arr2 = [111, 222, 333]
arr[1] = arr2
pp arr1 # => [0, [111, 222, 333], 2, 3, 4, 5, 6, 7, 8, 9]
# 注意: 配列外に追加もでき、存在しない部分はnilでうめられる
arr[15] = 100
pp arr # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, nil, nil, nil, nil, nil, 100]

# String
str1 = 'abcdefg'
str2 = 'BCD'
str1[1..3] = str2
pp str1
# 1文字選択の場合
str1 = 'abcdefg'
str2 = 'BCD'
str1[1] = str2
pp str1 # => "aBCDcdefg"
# 注意: 配列外には追加できず、IndexErrorが変える
str1[14] = 'Z' # => in `[]=': index 14 out of string (IndexError)
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?