Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoMethodError: undefined method `except' for Hash

Tags:

ruby

hash

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?

like image 284
Ajax Avatar asked Jun 26 '26 06:06

Ajax


2 Answers

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} 
like image 57
Leo Brito Avatar answered Jun 28 '26 00:06

Leo Brito


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.

like image 21
Amadan Avatar answered Jun 27 '26 22:06

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!