2

我正在使用axlsxgem 创建一个电子表格。我想在所有电子表格列上设置固定宽度,我需要调用该函数

def column_widths(*widths)
  widths.each_with_index do |value, index|
    next if value == nil
    Axlsx::validate_unsigned_numeric(value) unless value == nil
    find_or_create_column_info(index).width = value
  end
end

中定义的Axlsx::Worksheet具有任意数量的列宽。例如`sheet.column_width(20, 20, ..., 20)。我的方法调用看起来像

sheet.column_widths [20]*headers.length

并导致错误

ActionView::Template::Error (Invalid Data [20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20] for Invalid column width. must be [Fixnum, Integer, Float].

如何为未知数量的列动态创建正确的方法调用?

4

1 回答 1

1

您的问题是该方法column_widths是这样定义的:

def column_widths(*widths)
  # some stuff

*参数中存在的飞溅运算符*widths意味着您可以拥有从 1 到 N(其中 N > 1)的参数。您正在尝试将此方法与整数数组一起使用,而不是您应该将每个整数作为单个参数传递,例如:

sheet.column_widths(20, 20, 20, 20, #etc...

但这不是最好的方法。使用这些参数的一种更好的方法是同时使用 splatter 运算符:

sheet.column_widths(*[20]*headers.length)
                   #^ This is the splatter operator

飞溅运算符实用程序的一个非常明确的示例(在我的 IRB 控制台中,Ruby 1.9.3p489):

ann, marc, john = *['Ann', 'Marc', 'John']
# => ["Ann", "Marc", "John"] 
ann
# => "Ann"

关于飞溅运算符的一些内容:http: //4loc.wordpress.com/2009/01/16/the-splat-operator-in-ruby/

于 2014-10-14T17:45:19.650 回答