`Hash()` when creating a hash - ruby

I see many seemingly interchangeable ways to create a hash. The following all create the same hash:
w = {:one => 1, :two => 2}
x = Hash[:one => 1, :two => 2]
y = Hash.[](:one => 1, :two => 2)
z = Hash.send(:[], :one => 1, :two => 2)
huh = Hash(:one => 1, :two => 2)
As for Hash(:one => 1, :two => 2), I expect to find a :() method for Hash in the documentation. Along with the documented method ::[], shouldn't the documentation also list a ::() method?
If they are both just syntactic sugar, where is the latter method documented?

It's a method in Kernel (which contains other methods that you can call directly like Kernel.puts) - Kernel.Hash. Don't use it (it's not idiomatic).

Related

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

Built-in way to flip ruby hash associations

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}

What is the common way to handle optional method params?

I have a method in which i want to pass in dynamic params. The method is called in a loop and sometimes value2 is available and sometimes not.
What is the common way to handle optional method params?
my_method(:value1 => 1,
:value2 => 2 if foo, # this is not working
:value3 => 3)
I usually create a hash like this:
opts = {:value1 => 1,
:value3 => 3}
opts[:value2] = 2 if foo
my_method(opts)
The benefit of this approach is that everyone catches the if foo as it is a special case. Otherwise many programmers, like myself, will miss this at first glance and get confused why :value2 is not set.
Sometimes you have default settings, then you can use this approach:
default = {:value1 => 0,
:value2 => 0,
:value3 => 0}
opts = {:value1 => 1,
:value3 => 3}
my_method(default.merge(opts))
Or even better:
DEFAULT_OPTS = {:value1 => 0,
:value2 => 0,
:value3 => 0}
def my_method(opts)
opts = DEFAULT_OPTS.merge(opts)
# ...
end
my_method(...)

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]

Ruby - method parameters

My method:
def my_method=(attributes, some_option = true, another_option = true)
puts hello
end
When i try to call this, i get such error:
my_method=({:one => 'one', :two => 'two'}, 1, 1)
#you_code.rb:4: syntax error, unexpected ',', expecting ')'
#my_method=({:one => 'one', :two => 'two'}, 1, 1)
^
What's the problem?
Method with suffix punctuation = can have only one argument.
Otherwise, you must use send to invoke with multiple parameters.
send :'my_method=', {:a => 1}, 1, 1
Don't use parenthesis when invoking a method using the = syntactic sugar.
Invoke it like this:
mymethod= {:one => 'one', :two => 'two'}, 1, 1

Resources