Ruby on rails Ruby:从数组动态创建函数调用参数列表
我正在使用Ruby on rails Ruby:从数组动态创建函数调用参数列表,ruby-on-rails,ruby,axlsx,Ruby On Rails,Ruby,Axlsx,我正在使用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).wid
axlsx
gem创建一个电子表格。我想将所有电子表格列的固定宽度设置为,我需要调用该函数
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::工作表
中定义,列宽任意。例如,`表.列的宽度(20,20,…,20)。我的方法调用看起来像
sheet.column_widths [20]*headers.length
这就导致了错误
ActionView::Template::Error(无效列宽的无效数据[20,20,20,20,20,20,20,20]必须是[Fixnum,Integer,Float]。
如何为未知数量的列动态创建适当的方法调用?您的问题是方法
列宽的定义如下:
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
splatter操作符实用程序的一个非常明确的示例(在我的IRB控制台Ruby 1.9.3p489中):
关于splatter操作符的一些内容:关于sheet.column\u widths(*[20]*headers.length)
?这很有效。谢谢!你想发布一个答案吗?你也可以widths.flatten。每个\u都有索引
,使界面更灵活、更简洁。
ann, marc, john = *['Ann', 'Marc', 'John']
# => ["Ann", "Marc", "John"]
ann
# => "Ann"