Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting multiple key and value pairs from hash in Rails

Tags:

ruby

number = {:a => 1, :b => 2, :c => 3, :d => 4}

upon evaluation of certain condition i want to delete key-value pair of a,b,c

like image 575
akshay1188 Avatar asked Sep 09 '10 15:09

akshay1188


People also ask

Can a Hash key have multiple values?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

What is a Hash in rails?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.


2 Answers

number.delete "A"
number.delete "B"
number.delete "C"

Or, less performant but more terse:

number.reject! {|k, v| %w"A B C".include? k }
like image 197
Chris Heald Avatar answered Sep 28 '22 05:09

Chris Heald


or, more performant than second Chris' solution but shorter than first:

%w"A B C".each{|v| number.delete(v)}
like image 43
Pavel K. Avatar answered Sep 28 '22 07:09

Pavel K.