Tbpgr Blog

Ruby プログラマ tbpgr(てぃーびー) のブログ

Ruby | Hash | reject

概要

Hash#reject

詳細

Hashから条件に一致しない要素を抽出する

サンプルコード
# encoding: utf-8
require 'tbpgr_utils'

h = {
  hoge_key1: :hoge_value,
  hoge_key2: :hoge_value,
  hige_key: :hige_value,
  hage_key: :hage_value,
}

bulk_puts_eval binding, <<-EOS
h.reject {|k, v|v == :hoge_value}
h.reject {|k, v|v == :not_exists}
EOS
__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
出力
h.reject {|k, v|v == :hoge_value} # => {:hige_key=>:hige_value, :hage_key=>:hage_value}
h.reject {|k, v|v == :not_exists} # => {:hoge_key1=>:hoge_value, :hoge_key2=>:hoge_value, :hige_key=>:hige_value, :hage_key=>:hage_value}