Ruby 2D不同类型的数组

时间:2012-10-06 07:14:01

标签: ruby-on-rails ruby highcharts

如何声明字符串和int类型的2D数组?

我想做这样的事情

@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

1 个答案:

答案 0 :(得分: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