2014-05-13 4 views
1

로 구분 된 문자열의 배열을 변환 나는루비 해시

array.each do |e| 
    k = e.split(":").first 
    v = e.split(":").last 
    hash[k] = v 
end 

을 할 수

내가 알고

{"bob" => "12 elm st", "sally" => "100 digital ave", "tom" => "2324 elmhurst st"}. 

로 변환 할 필요가

["bob:12 elm st", "sally:100 digital ave", "tom:2324 elmhurst st"] 

배열을 거기되어 있습니다 이 일을 더 우아한 방법?

+0

[가능한 루비에서 배열을 해시로 변환하는 가장 좋은 방법은 무엇입니까] (http://stackoverflow.com/questions/39567/what-is-the-best-way-to-convert-an -array-to-a-hash-in-ruby) – Yossi

답변

7

Hash[]은 배열에서 해시를 생성합니다.

Hash[array.map {|el| el.split ':'}] 
6

저는 루비 2.1에 .to_h 메소드가 있다고 생각합니다.

그 때문에,

array.map { |i| i.split ':' }.to_h 

작동합니다.