2014-02-14 114 views
0

我有一串字母和數字組成的字符串:ZIP沒有產生正確的結果

directions = ur 
wieghts = 63 3 

我想他們哈希。然後,我希望得到的東西,如:

u is 63 
r is 3 

我這樣做:

d = Array.new 
d.push(directions.split("")) 
w = Array.new 
w.push(wieghts.split(/\s/)) 
@h = Hash[d.zip w] 

在節目之後,我調用包含這個zip類:

f = info[1].gethash 
f.each {|key, value| puts " #{key} is #{value}"} 

,但我得到:

["u", "r"] is ["63", "3"] 

我在做什麼錯?

+0

你的字符串和數字不是有效的Ruby對象。你的'@ h'沒用,它不被使用。什麼是'信息'?什麼是gethash?解釋所有變量。 – sawa

回答

1

變化如下

d = Array.new 
d.push(*directions.split("")) # splat the inner array 
w = Array.new 
w.push(*weights.split(/\s/)) # splat the inner array 

directions.split("")給你一個數組,你推到d,而你應該膿由directions.split("")創建的數組的元素。因此,爲了滿足這種需求,您必須使用splat運算符(*),就像我上面的*directions.split("")一樣。同樣的解釋需要使用*,與*weights.split(/\s/)

push(obj, ...) → ary

追加的讀資料 - 推到這個陣列的端部的給定的對象(一個或多個)

例子:

(arup~>~)$ pry --simple-prompt 
>> a = [] 
=> [] 
>> b = [1,2] 
=> [1, 2] 
>> a.push(b) 
=> [[1, 2]] # see here when I didn't use splat operator. 
>> a.clear 
=> [] 
>> a.push(*b) # see here when I used splat operator. 
=> [1, 2] 

一個建議,我認爲以下就足夠了:

d = directions.split("") # d = Array.new is not needed 
w = weights.split(/\s/) # w = Array.new is not needed 
@h = Hash[d.zip w] 
+1

非常感謝! – JKT

0

假設你有你的變量正確聲明:

directions = 'ur' 
weights = '63 3' 

然後,你可以做:

Hash[directions.chars.zip(weights.split)] 
相關問題