140
142

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] 便利な組み込みクラスのメソッド達(Array編)

Last updated at Posted at 2014-01-06

概要

パーフェクトRubyを読んでいて便利だと思ったもの一覧です。

Enumerable編
http://qiita.com/kidachi_/items/a00558cfb0a6a3e23f4b
Hash編
http://qiita.com/kidachi_/items/651b5b5580be40ad047e
String編
http://qiita.com/kidachi_/items/7b355eb355b2d1390cf5

配列の整形

compact

配列からnilを除去。

> [false, nil, 0, '', []].compact
=> [false, 0, "", []]

uniq

配列から重複要素を排除。

> %w(Ruby Python Java Ruby Python Java).uniq
=> ["Ruby", "Python", "Java"]

flatten

多次元配列を一次元にして返却。

> arr = ["Ruby", ["Python", ["Java", "C"]]]
> arr.flatten
=> ["Ruby", "Python", "Java", "C"]

transpose

二次元配列を行列と見立てて、行と列の入れ替えを行う。

> arr = [[1, 2, 3], ["Ruby", "Python", "Java"]]
> arr.transpose
=> [[1, "Ruby"], [2, "Python"], [3, "Java"]]

zip

二つの配列を行と列を入れ替えた上で結合する。

> arr1 = [1, 2, 3]
> arr2 = ["Ruby", "Python", "Java"]
> arr1.zip(arr2)
=> [[1, "Ruby"], [2, "Python"], [3, "Java"]]

要素の連結

join

要素を連結する。
引数に文字列を与えた場合は、それをセパレータとして連結する。

> %w(Ruby Python Java).join
=> "RubyPythonJava"
> %w(Ruby Python Java).join(', ')
=> "Ruby, Python, Java"

要素の取得

sample

与えた引数だけ、ランダムに要素を取り出す。

> arr = %w(Ruby Python Java C Smalltalk Brainfuck)
=> ["Ruby", "Python", "Java", "C", "Smalltalk", "Brainfuck"]
> arr.sample
=> "Python"
> arr.sample
=> "Brainfuck"
> arr.sample
=> "C"
> arr.sample(2)
=> ["Ruby", "Smalltalk"]
> arr.sample(2)
=> ["Smalltalk", "C"]

assoc

多次元配列から、キーを指定して要素を取り出す。

> arr = [[:ruby, 1], [:python, 2], [:java, 3]]
=> [[:ruby, 1], [:python, 2], [:java, 3]]
> arr.assoc(:ruby)
=> [:ruby, 1]

要素の追加と削除

pop, push, shift, unshift

> arr = ["Ruby", "Python", "Java"]
=> ["Ruby", "Python", "Java"]
# 末尾の要素を取り出す
> arr.pop
=> "Java"
# 破壊的
> arr
=> ["Ruby", "Python"]
# 末尾に要素を追加する
> arr.push("Java")
=> ["Ruby", "Python", "Java"]
# 破壊的
> arr
=> ["Ruby", "Python", "Java"]

# 先頭の要素を取り出す
> arr.shift
=> "Ruby"
# 破壊的
> arr
=> ["Python", "Java"]
# 先頭に要素を追加する
> arr.unshift("Ruby")
=> ["Ruby", "Python", "Java"]
# 破壊的
> arr
=> ["Ruby", "Python", "Java"]

※ スタック(FirstIn, LastOut/先入れ後出し)は
pop/pushもしくはshift/unshift

※ キュー(FirstIn, FirstOut/先入れ先出し)は
pop/unshiftもしくはpush/shift

140
142
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
140
142

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?