3
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]要素を拒否できるrejectメソッド

Posted at

はじめに

Ruby初学者です。
今回はrejectについて、メモしていきます。

rejectとは

公式リファレンスではrejectについて以下のように説明されています。

各要素に対してブロックを評価し、その値が偽であった要素を集めた新しい配列を返します。条件を反転させた select です。 ブロックを省略した場合は、各要素に対しブロックを評価し偽になった値の配列を返すような Enumerator を返します。※配列型の場合

またハッシュ型の場合でもほぼ使い方は同じで、ハッシュを返すということ以外は同じとなります。
尚、rejectは非破壊的メソッドとなります。

使い方

rejectメソッドを使った例を以下に示します。

配列の場合

[1,2,3].reject {|i| i==1}
=> [2, 3]

ハッシュの場合

{"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4"}.reject {|k,v| v=="4" }
=> {"a"=>"1", "b"=>"2", "c"=>"3"}

使用例

word = [1,2,3]
word = word.reject {|i| i==1 }
p word
=> [2, 3]

# 破壊的メソッドの場合
word = [1,2,3]
word.reject! {|i| i==1 }
p word
=> [2, 3]

参考

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