2013-10-24 70 views
0

我正在使用Rhomobile并试图动态地为Alert.show_popup的按钮的ID和标题生成一个哈希,但我并没有完全明白。我想最终的结果是什么是,实际上是:在JSON中创建红宝石的多维数组或哈希

Alert.show_popup({ 
    :message => 'Please Select Appropriate Address:', 
    :title => 'Get Nearby...', 
    :icon => :info, 
    :buttons => [ 
     {'id' => '1', 'title' => 'Address 1'}, 
     {'id' => '2', 'title' => 'Address 2'}, 
     {'id' => '3', 'title' => 'Address 3'}, 
     {'id' => '4', 'title' => 'Address 4'} 
    ], 
    :callback => url_for(:action => :on_addressidentified_popup) 
    } 
) 

我已经尝试了一些方法,但都没有工作(建立一个字符串,它看起来像一个哈希和try_convert等)。这是我尝试过的最近的一个,它看起来很接近,但还很远:

nearbyaddresses = Rho::JSON.parse(@params['body']) 

    h = {} 

    nearbyaddresses.each do |location| 
    h[intIndex] = {} 
    h[intIndex][:id] = intIndex.to_s 
    h[intIndex][:title] = location["Address"].to_s 

    intIndex = intIndex + 1 
    end 

    Alert.show_popup({ 
    :message => 'Please Select Appropriate Address:', 
    :title => 'Get Nearby...', 
    :icon => :info, 
    :buttons => h, 
    :callback => url_for(:action => :on_addressidentified_popup) 
    } 
) 

任何ruby向导都可以帮助我吗?

+0

你确定你想要一个哈希? 'buttons'是你第一个例子中的一个数组。 –

回答

0

如何

nearby_addresses_list = Rho::JSON.parse(@params['body']) 

buttons_list = nearby_addresses_list.collect.each_with_index {|address, i| 
     {'id' => i, 'title' => address} #not sure if you need to dig into this at all. 
} 

这应该与此值

[{'id' => 0, 'title' => nearby_addresses_list[0]}, 
{'id' => 1, 'title' => nearby_addresses_list[1]} 
{'id' => 2, 'title' => nearby_addresses_list[2]} 
{'id' => 3, 'title' => nearby_addresses_list[3]}] 

离开buttons_list如果你想在ID与1日开始,改变收集声明的身体{'id' => i+1, 'title' => address}

然后,只需将buttons_list添加为键:按钮的值即可。

Alert.show_popup({ 
    :message => 'Please Select Appropriate Address:', 
    :title => 'Get Nearby...', 
    :icon => :info, 
    :buttons => buttons_list, 
    :callback => url_for(:action => :on_addressidentified_popup) 
    }) 

如果你看到你提到的第一个期望的输出,你说的是亲密的代码之间的怪事,是它也许是你使用的按键符号代码(:ID),和你想要的输出中的字符串(“ID”)?

0

下面是我如何解决这个问题。就像一个魅力...

intIndex = 0 
    nearbyaddresses = Rho::JSON.parse(@params['body']) 
    @@nearbyAddresses = nearbyaddresses 

    button_array = []   

    nearbyaddresses.each do |location| 
    opt = {'id' => intIndex.to_s, 'title' => location["Address"] } 
    button_array << opt 

    intIndex = intIndex + 1 
    end 

    Alert.show_popup({ 
    :message => 'Please Select Appropriate Address:', 
    :title => 'Get Nearby...', 
    :icon => :info, 
    :buttons => button_array, 
    :callback => url_for(:action => :getselectedaddress) 
    } 
)