2
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?

More than 3 years have passed since last update.

[Ruby]select,select!で配列やハッシュを抽出する

Posted at

はじめに

Ruby学習者です。
本記事はselectを使って配列を抽出したものです。
破壊的メソッドのselect!についても記述します。
以下公式ドキュメントです

selectの使用例

###1.配列の場合
even?はレーシバーが偶数の場合にtrueを返すメソッドです

list = [1,2,3,4,5]
list = list.select { |num| num.even? }

p list => [2, 4]

###2.ハッシュの場合

hash = { "a" => 1, "b" => 2, "c" => 3 }
hash = hash.select {|k,v| v.even? }  

p hash {"b"=>2}

select!の使用例

selectには破壊的メソッドselect!も用意されています。
破壊的メソッドはオブジェクトそのものを変更するものなのでlist=で代入する必要がなくなります。

###1.配列の場合

list = [1,2,3,4,5]
list.select! { |num| num.even? }

p list => [2, 4]

###2.ハッシュの場合

hash = { "a" => 1, "b" => 2, "c" => 3 }
hash.select! {|k,v| v.even? }  

p hash {"b"=>2}

##応用
selectを応用した、例を記述していきます。

list =  ["tokorozawa", "yamada", "oyama", "yazawa"]
 
list.select! { |x|
  x.include?("zawa")
}
p list
=> ["tokorozawa", "yazawa"]
list = [1,2,3,4,5]
list.select! { |num| num > 3 }

p list => [4, 5]

まとめ

  • selectを使うと配列やハッシュを抽出できる
  • 他のメソッドと組み合わせるとさまざまなデータ処理ができる
2
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
2
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?