2013-10-24 71 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) 
    } 
)