Is there a more efficient way to turn an array into a hash?

I think my method is a bit awkward, and that there will probably be one liner that I am missing. Ideas?

def _to_hash hsh = {} self.each_slice(2){|v| hsh[v[0]] = v[1]} hsh end 1.9.3-p0 :003 > ["a", 1, "b", 2]._to_hash { "a" => 1, "b" => 2 } 
+4
source share
2 answers

You need a hash statement. []:

 > Hash["a", 1, "b", 2] => {"a"=>1, "b"=>2} 
+3
source

@phiggy is correct, but also remember that you can use the splat operator:

 a = ["a", 1, "b", 2] Hash[*a] #=> {"a"=>1, "b"=>2} 
+4
source

Source: https://habr.com/ru/post/1385811/


All Articles