Ruby
array

[Ruby]あまり見ないけどたまに便利なメソッド[Array編]

More than 5 years have passed since last update.


countにブロックを渡す

[1,2,3,4,5].count(&:even?)

# => 2


nilを消す

[1, nil, "xyz", 3, nil, "hoge"].compact

# => [1, "xyz", 3, "hoge"]


逆方向にeach

name = %w(naohiko mori)

name.each(&method(:puts))
# => "naohiko" "mori"
name.reverse_each(&method(:puts))
# => "mori" "naohiko"


ゼロを消す

points = [1,2,0,4,0,0,3]

points.select(&:nonzero?)
# => [1,2,4,3]
points.reject(&:zero?)
# => [1,2,4,3]


適当にピックアップする

%w(aaa bbb ccc ddd eee).sample

# => "ddd"


同じ処理を繰り返す

spell = %w(ventra ventra space people)

spell.each{|word| puts word}
# => "ventra" "ventra" "space" "people"
spell.cycle(3){|word| puts word}
# => "ventra" "ventra" "space" "people" "ventra" "ventra" "space" "people" "ventra" "ventra" "space" "people"

引数を省略すると無限に繰り返すので注意。


場合の数を作る

names = %w(taro hanako nao)

domains = %w(@sample.com @foobar.co.jp)
names.product domains
# => [["taro", "@sample.com"],["taro", "foobar.co.jp"],["hanako", "@sample.com"],["hanako", "foobar.co.jp"],["nao", "@sample.com"],["nao", "foobar.co.jp"]]