2012-10-06 65 views
0

我如何聲明一個類型爲string和int的二維數組?Ruby不同類型的二維數組

我想要做這樣的事情

@products.each do |p| 
    array = [p.title, p.price] 
end 

,但我得到一個錯誤說不能把字符串轉換爲int

的問題是,我只能調用一次f.series(),我需要一個數組來保存我的數據

f.series(:name => 'Product Sales', :data => array) 

我想按照這個代碼創建一個餅圖

https://github.com/bakongo/highcharts_plugin_sample_graphs/blob/master/app/controllers/graphs_controller.rb

def pie_chart 
@categories = generate_categories(6) 
@numbers = generate_numbers(6) 
assoc = [] 
@categories.each_with_index {|c,i| assoc << [c, @numbers[i]]} 

@highchart = HighChart.new('graph') do |f| 
    f.title(:text => 'Flowers in Yard') 
    f.options[:chart][:defaultSeriesType] = "pie" 
    f.options[:x_axis][:categories] = @categories 
    f.series(:type => 'pie', :name => 'Flower Presence', :data => assoc) 
end 

def generate_numbers(number) 
    numbers = [rand(number)] 
    (1...number).each_with_index {|v, i| numbers << (rand(number)+1)} 
    numbers 
end 

def generate_categories(number) 
    cats = ['Sunflower', 'Magnolia', "Rose", 'Lily', 'Tulip', 'Iris'] 
    cats[0...number] 
end 

回答

2

在Ruby中,你可以在單一陣列中保存不同類型的元素像下面

arr = [1, 1.0, "This is a String", {abc: pqr}, [6]] 
#arr[0].class = Fixnum 
#arr[1].class = Float 
#arr[2].class = String 
#arr[3].class = Hash 
#arr[4].class = Array 

所以,如果你想保存數組的數組像以下

​​

以下使用

array = [] 
@products.each do |p| 
    array << [p.title, p.price] 
end 

或只是

array = @products.collect{|p| [p.title, p.price]} 

編輯以顯示訪問二維數組

arr = [["value1", 1.0], ["value2", 2.0]] 
#arr[0] = ["value1", 1.0] 
#arr[0][0] = "value1" 
#arr[0][1] = 1.0 
#arr[1] = ["value2", 2.0] 
#arr[1][0] = "value2" 
#arr[1][1] = 2.0