While using except on Hash in Ruby,
d = {}
d["a"]=1234
d["b"]=34
d["c"]=3
d.except(:b,:c)
I am getting NoMethodError:
NoMethodError: undefined method `except' for {"a"=>1234, "b"=>34, "c"=>3}:Hash from (irb):6 from
/Users/niranjan/.rvm/rubies/ruby-1.9.3-p551/bin/irb:12:in `<main>'
What am I doing wrong?
except is a Rails method (ActiveSupport to be exact). Your code does not reproduce that error when executing in Rails console:
> d = {}
# => {}
> d["a"]=1234
# => 1234
> d["b"]=34
# => 34
> d["c"]=3
# => 3
> d.except(:b,:c)
# => {"a"=>1234, "b"=>34, "c"=>3}
There is no Hash#except. You can implement it as follows:
d.reject { |k, v| ["b", "c"].include? k }
# => {"a"=>1234}
Note that it is not a Hash with indifferent access; "b" is not the same thing as :b.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With