2013-04-04 52 views

回答

0
def show(*a) 
p a 
if a.length.even? == true 
    p Hash[*a] 
else 
    p "hash conversion not possible" 
end 
end 

show(1,2,3,4) 
show(1,2,3) 

輸出:

[1, 2, 3, 4] 
{1=>2, 3=>4} 

[1, 2, 3] 
"hash conversion not possible" 

編輯:

從OP的評論這裏是代碼OP可以使用:

def add(*arg) 
    @entries = {} 
    arg.each_slice(2) do |a| @entries[a.first] = a.last end 
    p @entries 
end 

add(1,2,3,4) 

輸出:

{1=>2, 3=>4} 
+0

你好。我使用「每個」這個參數,並得到錯誤。如何使用「每個」僅用於數組?如何檢查參數? – 2013-04-04 09:43:58

+0

這裏是我的代碼: def add(defs) defs.each do | word,definition | @entries [word] = definition end end – 2013-04-04 09:44:46

+0

@JohnOggy'each'只能帶一個參數。 – 2013-04-04 09:54:51