4

I think that my method is a little clumsy, and that there is likely to be a one-liner that I'm 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
}
1

2 Answers 2

4

@phiggy's method is correct, but also remember that you can use a splat operator:

a = ["a", 1, "b", 2]
Hash[*a] #=> {"a"=>1, "b"=>2}
Sign up to request clarification or add additional context in comments.

Comments

3

You want Hash's .[] operator:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.