【发布时间】:2018-09-01 19:36:20
【问题描述】:
我正在尝试像这样存储和输出方法输入:
Want [ ["email addresses"], ["phone numbers"], ["names"] ] - > [["bobsmith@example.com","sallyfield@example.com"],["555-555-5555","111-111-1111"],["Bob Smith","Sally Field"]]
这是我的代码:
def hash_2_array contacts
2 # Extract like info from each hash into arrays
3 stringArr = Array.new(3,Array.new(2)) #=> [ [ nil,nil] , [nil,nil] , [nil,nil] ]
4
5 if contacts.empty?
6 return nonsense = Array.new(3, Array.new)
7 else
8 n=0 #name counter
9 e=0 #email counter
10 p=0 #phone counter
11 contacts.each do |key, value|
12 stringArr[2][n] = key.to_s #adds name to array
13 n+=1
14 value.each do |key2, value2|
15 if key2.to_s.eql?("email")
16 stringArr[0][e] = value2.to_s #adds email address to array
17 e+=1
18 else
19 stringArr[1][p] = value2.to_s #adds phone number to array
20 p+=1
21 end
22 end
23 end
24 end
25 return stringArr
26 end
27
28
29 hash_2_array({:"Bob Smith"=>{:email=>"bobsmith@example.com", :phone=>"555-555-5555"}, :"Sally Field"=>{:email=>"sallyfield@example.com", :phone=>"111-111-1111"}})
返回:
got: [["555-555-5555", "111-111-1111"], ["555-555-5555", "111-111-1111"], ["555-555-5555", "111-111-1111"]]
这真的很令人困惑,为什么它不只是分配我指定的数组中的索引。我认为这段代码以前有效,但现在它以某种方式被破坏了。任何帮助都会很棒
【问题讨论】:
-
读者可能想运行你的代码,不管有没有修改。为此,步骤 1 是剪切和粘贴。第 2 步(这不是必需的)是删除所有行号。呈现代码时请不要包含行号、IRB 提示等。