Built-in way to flip ruby hash associations - ruby

Assuming I have a ruby has with one-to-one correspondence, is there some built-in method to reverse associations in a ruby hash? I would prefer doing this without explicitly looping through the keys.
For example, suppose I have:
a = {1 => "Foo", 2 => "Bar"}
a.reverse_association
a # ---> {"Foo" => 1, "Bar" => 2}

Yes, use Hash#invert:
h = {a: 1, b: 2}
h.invert #=> {1 => :a, 2 => :b}

Related

How can I place a new key value pair to the top of a hash?

I have some hash:
> my_hash = {b: "foo", c: "bar"}
I add a new key and it goes to the end:
> my_hash[:a] = "baz"
=> "baz"
> my_hash
=> {b: "foo", c: "bar", a: "baz"}
But I want it to go to the front:
> my_hash
=> {a: "baz", b: "foo", c: "bar"}
Thanks in advance
Theoretically hash elements' order is not important, but who am I to judge your reasons you might have valid reasons we don't know about. You can use Hash#merge for that:
> {a: "baz"}.merge(my_hash)
=> {:a=>"baz", :b=>"foo", :c=>"bar"}
> my_hash = {a: "baz"}.merge(my_hash)
=> {:a=>"baz", :b=>"foo", :c=>"bar"}
> my_hash
=> {:a=>"baz", :b=>"foo", :c=>"bar"}

setter method for hash with send()

Is it possible in Ruby to call setter method for hash with send method?
Just like I can do this:
h = {a: "a", b: "b"}
h.send(:[], :a)
and GET value "a" out of this hash, can I set value for key :a?
Yes. The method then is []=
Example:
hash = {:a => 1, :b => 2}
hash.send :[]=, :a, 3
hash # => {:a => 3, :b => 2}

Ruby, turn array of hashes into single hash

I have the following Array of Hashes:
a = [{:a => 1, :b => "x"}, {:a => 2, :b => "y"}]
I need to turn it into:
z={"x" => 1, "y" => 2}
or:
z={1 => "x", 2 => "y"}
Can I do this in a clean and functional way?
Something like this:
Hash[a.map(&:values)] # => {1=>"x", 2=>"y"}
if you want the other way:
Hash[a.map(&:values).map(&:reverse)] # => {"x"=>1, "y"=>2}
incorporating the suggestion from #squiguy:
Hash[a.map(&:values)].invert

How to add new item to hash

I don't know how to add new item to already existing hash. For example, first I construct hash:
hash = {item1: 1}
After that, I want to add item2, so after this I have hash like this:
{item1: 1, item2: 2}
I don't know what method to do on hash. Could someone help me?
Create the hash:
hash = {:item1 => 1}
Add a new item to it:
hash[:item2] = 2
If you want to add new items from another hash - use merge method:
hash = {:item1 => 1}
another_hash = {:item2 => 2, :item3 => 3}
hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3}
In your specific case it could be:
hash = {:item1 => 1}
hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2}
but it's not wise to use it when you should to add just one element more.
Pay attention that merge will replace the values with the existing keys:
hash = {:item1 => 1}
hash.merge({:item1 => 2}) # {:item1=>2}
exactly like hash[:item1] = 2
Also you should pay attention that merge method (of course) doesn't effect the original value of hash variable - it returns a new merged hash. If you want to replace the value of the hash variable then use merge! instead:
hash = {:item1 => 1}
hash.merge!({:item2 => 2})
# now hash == {:item1=>1, :item2=>2}
hash.store(key, value) - Stores a key-value pair in hash.
Example:
hash #=> {"a"=>9, "b"=>200, "c"=>4}
hash.store("d", 42) #=> 42
hash #=> {"a"=>9, "b"=>200, "c"=>4, "d"=>42}
Documentation
It's as simple as:
irb(main):001:0> hash = {:item1 => 1}
=> {:item1=>1}
irb(main):002:0> hash[:item2] = 2
=> 2
irb(main):003:0> hash
=> {:item1=>1, :item2=>2}
hash[key]=value
Associates the value given by value with the key given by key.
hash[:newKey] = "newValue"
From Ruby documentation:
http://www.tutorialspoint.com/ruby/ruby_hashes.htm
hash_items = {:item => 1}
puts hash_items
#hash_items will give you {:item => 1}
hash_items.merge!({:item => 2})
puts hash_items
#hash_items will give you {:item => 1, :item => 2}
hash_items.merge({:item => 2})
puts hash_items
#hash_items will give you {:item => 1, :item => 2}, but the original variable will be the same old one.
Create hash as:
h = Hash.new
=> {}
Now insert into hash as:
h = Hash["one" => 1]

Deleting multiple key and value pairs from hash in Rails

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
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 }
or, more performant than second Chris' solution but shorter than first:
%w"A B C".each{|v| number.delete(v)}
ActiveSupport that is a part of Rails comes with several built-in methods can help you to achieve your goal.
If you just want to delete some key-value pairs, you can use Hash#except!
number.except!(:a, :b, :c)
If you want to keep the original hash, then use Hash#except
new_hash = number.except!(:a, :b, :c)
new_hash # => {:d=>4}
number # => {:a=>1, :b=>2, :c=>3, :d=>4}
You also can go with Rails-free way:
new_hash = number.dup.tap do |hash|
%i[a b c].each {|key| hash.delete(key)}
end
new_hash # => {:d=>4}
number # => {:a=>1, :b=>2, :c=>3, :d=>4}
P.S.: the last code example is very slow, I'm just providing it as an alternative.

Resources