返回值未在Ruby中提取

def get_dept_class_type departments, classifications, types = [["-- select one --"]] * 3 Department.all.each do |d| departments << d.name end Classification.all.each do |c| classifications << c.name end Type.all.each do |t| types << t.name end return departments, classifications, types end def new @departments, @classifications, @types = get_dept_class_type end 

大家好,

上面是我在Ruby中的代码,用于将“get_dept_class_type”函数的返回值赋给“def new”实例变量。 问题是,“get_dept_class_type”函数的返回值未被提取,因此所有实例变量都具有相同的值。 每个实例变量都是html格式的select标签的包含值。

部门,分类,类型选择标签的值具有相同的内容:

  • 信息技术
  • 行政部门
  • 内部使用
  • 绝密
  • 机密
  • 上市
  • 政策
  • 程序手册

请帮我解决这个问题。 先谢谢你。

你的主要问题是 –

  departments, classifications, types = [["-- select one --"]] * 3 

改为 –

 departments, classifications, types = Array.new(3) { ["-- select one --"] } 

让它调试: –

 ([[]] * 3).map(&:object_id) # => [72506330, 72506330, 72506330] 

 Array.new(3) { [] }.map(&:object_id) # => [76642680, 76642670, 76642520] 

你可以看到,所有内部对象基本上都是相同的对象。 基本上你已经创建了一个数组数组,比如a ,其中所有元素数组都是同一个对象。 因此,如果你修改a[0] ,你可以在检查a[1]a[2]时看到相同的变化。 但是如果你创建了相同的数组数组, a as, Array.new(3) { [] } ,那么a的每个内部元素数组都将是不同的对象。 因此,如果你说修改a[0] ,那么a[1]a[2]将是完整的。

值得阅读Common gotchas