Last active
August 29, 2015 14:04
-
-
Save kyuden/fabce1d756ecd5e7c651 to your computer and use it in GitHub Desktop.
Array#select(Enumerable#select), Hash#select
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hash#find_all | |
Hash#select | |
h = {a: 1, b: 2, c: 3} | |
h.find_all { |key, value| value.odd? } #=> [[:a, 1], [:c, 3]] | |
h.select { |key, value| value.odd? } #=> {:a=>1, :c=>3} | |
Array#select | |
Array#select | |
ary = (1..3) | |
ary.select { |i| i.odd? } #=> [1, 3] | |
ary.find_all { |i| i.odd? } #=> [1, 3] | |
まとめ | |
配列、ハッシュから条件に一致した要素を抽出する | |
Hash#find_allはハッシュがレシーバでも配列で返す、なにがなんでも配列が良ければfind_all | |
レシーバに合わせて返す値を変えて欲しければselect | |
因みにselectの反対はreject | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment