Trương Văn Học Trương Văn Học - 8 months ago 24
Ruby Question

Delete element using key in hash with self

I'm learning hash in Ruby.
I'm trying to iterate a hash without assigning it to any variable and delete its elements.

{a: 1, b: 2, c: "Hello"}.each{|k,v| self.delete(k)}
. I get this error

2.3.0 :001 > {a: 1, b: 2, c: "Hello"}.each {|k,v| self.delete(k)}
NoMethodError: undefined method `delete' for main:Object
from (irb):1:in `block in irb_binding'
from (irb):1:in `each'
from (irb):1
from /usr/local/rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'

I also tried to replace
but it didn't work neither. Is there anyway I can use methods of hash (like
) without assigning the hash to a variable (like
hash_var.each {|k,v| hash_var.delete(k)}
)? I'm using c9 IDE.


In ruby, self variable contains a link to the object that contains your block. In your sample this is main object. So, you right, you must explicitly scpecify variable hash_var in your block.

Also, it's seems you want to delete all keys from your hash. So use delete_if instead of each to delete selected items of the hash

{a: 1, b: 2, c: "Hello"}.delete_if{|k,v| your_condition}


Or, if you want delete all keys from hash and get array from it you must use values method:

 {a: 1, b: 2, c: "Hello"}.values