Created
October 30, 2015 04:14
-
-
Save brijeshgpt7/6ddc84145555a3874abb to your computer and use it in GitHub Desktop.
Advance ruby hash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> [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"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://www.korenlc.com/nested-arrays-hashes-loops-in-ruby/