未在 Ruby 中提取返回值 [英] Return values were not extracted in Ruby

查看:42
本文介绍了未在 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 标签的包含值.

above is my code in Ruby to assign the return values from "get_dept_class_type" function to "def new" instance variables. The problem is, the return values from the "get_dept_class_type" function were not extracted, So all instance variables have the same values. Each instance variable is the containing value of a select tag in html form.

department、classification、type select 标签的值有这些相同的内容:

The values of department, classification, type select tags have these the same content:

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

请帮我解决这个问题.提前谢谢你.

Please it help me to figure this out. Thank you in advanced.

推荐答案

您的主要问题是 -

 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 相同的数组数组,Array.new(3) { [] },则 a<的每个内部元素数组/code>,将是不同的对象.因此,如果您说修改 a[0],那么 a[1]a[2] 将保持不变.

You can see, that all the inner objects are basically same object. Basically you have created an array of array, say a, where all the element arrays are same object. Thus if you have modified, say a[0], you can see the same change when you would inspect a[1] or a[2]. But if you do create the same array of array, a as , Array.new(3) { [] }, then each inner element array of a, will be different object. Thus if you say modify a[0], then a[1] and a[2] will be intact.

值得一读常见问题.

这篇关于未在 Ruby 中提取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆