6
2

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.

BitStarAdvent Calendar 2017

Day 7

知っててよかったRubyメソッド

Last updated at Posted at 2017-12-07

みなさんはじめまして。
株式会社BitStarでエンジニアインターン
をしている塩原です。

Array

each_with_index

配列のkeyとvalueを両方繰り返す。

> ["りんご", "みかん", "ぶどう"].each_with_index do |value, index|
>   puts "#{index}: #{value}"
> end
0: りんご
1: みかん
2: ぶどう

all?

配列のすべての要素が真であればtrueを返す

> [true, true, true].all?
=> true
> [true, true, false].all?
=> false

none?

配列の要素が全て偽であればtrueを返す。

> [false, false, false].none?
=> true
> [true, true, false].none?
=> false

any?

配列の要素のうち一つでも真であればtrueを返す。

> [true, true, false].any?
=> true
> [false, false, false].any?
=> false

one?

配列の要素のうち一つだけ真であればtrueを返す。

> [false, false, true].one?
=> true
> [false, false, false].one?
=> false
> [false, true, true].one?
=> false

sample

配列のなかからランダムにひとつ返す

> ["りんご", "みかん", "ぶどう"].sample
=> "りんご"
> ["りんご", "みかん", "ぶどう"].sample(2)
=> ["みかん", "ぶどう"]

zip

複数の配列をひとつにまとめる

> arr1 = [1, 2, 3]
> arr2 = [4, 5]
> arr3 = [6, 7, 8, 9]
> p arr1.zip(arr2, arr3)
=> [[1, 4, 6], [2, 5, 7], [3, nil, 8]]

Hash

has_key?

keyがふくまれていればtrueを返す

> { a: "x", b: "y", c: "z" }.has_key?(:b)
=> true

> { a: "x", b: "y", c: "z" }.has_key?(:z)
=> false

invert

キーとバリューを入れ替える

> hash = { a: "x", b: "y", c: "z" }
> hash.invert
=> {x: "a", y: "b", z: "c"}

merge

ハッシュを結合する

> hash1 = { a: "x", b: "y", c: "z" }
> hash2 = { d: 1, f: 2, g: 3 }
> hash3 = hash1.merge(hash2)
> puts hash3
=> {:a=>"x", :b=>"y", :c=>"z", :d=>1, :f=>2, :g=>3}

partition

条件に一致する値と条件に一致しない値をそれぞれ別々の配列に振り分ける。

> [1, 2, 3].partition{ |x| x % 3 == 0 }
=> [[3], [1, 2]]
6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?