Skip to content

Instantly share code, notes, and snippets.

@brijeshgpt7
Created October 30, 2015 04:14
Show Gist options
  • Save brijeshgpt7/6ddc84145555a3874abb to your computer and use it in GitHub Desktop.
Save brijeshgpt7/6ddc84145555a3874abb to your computer and use it in GitHub Desktop.
Advance ruby hash
> [1,2,3].map{ |i| i+1 }
=> [2, 3, 4]
_______________________________________________________________
> { "x" => 1, "y" => 2, "z" => 3 }.map{ |k,v| k.to_sym => v }
SyntaxError: (irb):2: syntax error, unexpected tASSOC, expecting '}'
{ "x" => 1, "y" => 2, "z" => 3 }.map{ |k,v| k.to_sym => v }
from /home/smeagol/.rvm/rubies/ruby-1.9.3-p429/bin/irb:16:in `<main>'
____________________________________________________________________________________
> { "x" => 1, "y" => 2, "z" => 3 }.map{ |k,v| { k.to_sym => v } }
=> [{:x=>1}, {:y=>2}, {:z=>3}]
______________________________________________________________________________________
> { "x" => 1, "y" => 2, "z" => 3 }.\
> inject({}){ |hash, (k, v)| hash.merge( k.to_sym => v ) }
=> {:x=>1, :y=>2, :z=>3}
> # if you prefer big-data parlance, the preferred term is reduce, not inject.
> # Either way, Ruby doesn't care - they do the same thing.
> { "x" => 1, "y" => 2, "z" => 3 }.\
> reduce({}){ |hash, (k, v)| hash.merge( k.to_sym => v ) }
=> {:x=>1, :y=>2, :z=>3}
_________________________________________________________________________________________
class Hash
def hmap(&block)
self.inject({}){ |hash,(k,v)| hash.merge( block.call(k,v) ) }
end
end
x = { "x" => 1, "y" => 2 }
x.hmap{ |k,v| { k.to_sym => v.to_s } }
=> {:x => "1", :y => "2"}
@brijeshgpt7
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment