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] 配列のメソッド

Posted at

要素を加える

先頭に追加 unshift

irb
>> arr = %w(た ま)
=> ["た", "ま"]
>> arr.unshift("あ") # 配列の先頭に要素を追加
=> ["あ", "た", "ま"]

末尾に追加 push

irb
>> arr = [1, 2]
=> [1, 2]
>> arr.push(3)
=> [1, 2, 3]
>> arr << 4 # arr.push(4) と同じ挙動
=> [1, 2, 3, 4]

連結

配列同士を連結 concat

irb
>> a = [1, 2]
=> [1, 2]
>> b = [3, 4]
=> [3, 4]
>> a.concat(b)
=> [1, 2, 3, 4]

要素を取り除く

要素がnilのものを取り除く compact

irb
>> a = [1, nil, 2]
=> [1, nil, 2]
>> a.compact
=> [1, 2]

配列から指定した要素を取り除く delete

irb
>> sushi = ["マグロ", "わさび"]
=> ["マグロ", "わさび"]
>> sushi.delete("わさび")
=> "わさび"
>> sushi
=> ["マグロ"] # わさびが取り除かれている

指定したインデックスの要素を取り除く delete_at

irb
>> arr = [1, 2, 3]
=> [1, 2, 3]
>> arr.delete_at(1)
=> 2
>> arr
=> [1, 3]

ブロックを評価しtrueの場合は要素を取り除く delete_if

irb
>> num = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> num.delete_if {|n| n % 2 == 0} # 偶数を取り除く
=> [1, 3, 5, 7, 9]
>> num
=> [1, 3, 5, 7, 9]

指定された部分を取り除き、取り除いた値を返す slice

irb
>> a = (1..5).to_a
=> [1, 2, 3, 4, 5]
>> a.slice(1, 3)
=> [2, 3, 4]

重複する要素を削除 uniq

irb
>> a = [1, 1, 2]
=> [1, 1, 2]
>> a.uniq
=> [1, 2]

先頭を取り除き、取り除いた値を返す shift

irb
>> a = ["頭", "胴体", "尻尾"]
=> ["頭", "胴体", "尻尾"]
>> a.shift
=> "頭"
>> a
=> ["胴体", "尻尾"]

末尾を取り除き、取り除いた値を返す pop

irb
>> a = ["a", "b", "\n"]
=> ["a", "b", "\n"]
>> a.pop
=> "\n"
>> a
=> ["a", "b"]

要素を置き換える

要素をブロックの条件に応じて置き換える collect, map

irb
>> name = ["Alice", "Bob"]
=> ["Alice", "Bob"]
>> name.map {|s| s + "-san"}
=> ["Alice-san", "Bob-san"]

要素を引数に応じて置き換える fill

irb
>> a = (1..5).to_a
=> [1, 2, 3, 4, 5]
>> a.fill(0)
=> [0, 0, 0, 0, 0]
irb
>> a = (1..5).to_a
=> [1, 2, 3, 4, 5]
>> a.fill("a", 1, 3) # インデックス1からスタートして要素3個分を"a"に置き換える
=> [1, "a", "a", "a", 5]

配列を平坦化(= 入れ子構造を解除)

irb
>> a = [1, [2, 3], [4, [5], 6]]
=> [1, [2, 3], [4, [5], 6]]
>> a.flatten
=> [1, 2, 3, 4, 5, 6]

要素を並べ替える

要素を逆順にする reverse

irb
>> a = (1..5).to_a
=> [1, 2, 3, 4, 5]
>> a.reverse
=> [5, 4, 3, 2, 1]

ブロックで指定した順番に並べ替え sort

irb
>> a = [2, 4, 0]
=> [2, 4, 0]
>> a.sort # 昇順
=> [0, 2, 4]
irb
>> words = %w(apple banana chocolate)
=> ["apple", "banana", "chocolate"]
>> words.sort {|a, b| a.length <=> b.length} # 長さの短い順
=> ["apple", "banana", "chocolate"]
>> words.sort {|a, b| b.length <=> a.length} # 長さの長い順
=> ["chocolate", "banana", "apple"]

ブロックで並べ替えの基準を決めてソートする sort_by

irb
>> words = ["aaa", "aa", "a"]
=> ["aaa", "aa", "a"]
>> words.sort_by {|w| w.length}
=> ["a", "aa", "aaa"]

参考

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?