0

如何声明字符串和 int 类型的二维数组?

我想做这样的事情

@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
4

1 回答 1

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

因此,如果您想保存数组数组,如下所示

[["value1", 1.0], ["value2", 2.0]]

使用以下

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

要不就

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

编辑以显示对 2D 阵列的访问

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
于 2012-10-06T07:40:00.043 回答