0

如果我做:

name_array = Model.column_names
name_array.delete_if {|name| ["id","created_at","updated_at"].include?(name)}
pp Model.column_names

该命令将返回一个没有, &列名Model.column_names的数组。我的假设是删除名称而不是 Model.column_names 数组。idcreated_atupdated_atname_array

导轨 3.0.13 红宝石 1.9.3

4

3 回答 3

5

请参阅阵列文档delete_if

删除块计算为 true 的每个 self 元素。每次调用块时数组都会立即更改,而不是在迭代结束后更改。

因此,当您从中删除元素时name_array,实际上是在从中删除它们,Model.column_names因为它们指向同一事物。

如果您不想这样做,请在删除之前复制数组

name_array = Model.column_names.dup
name_array.delete_if {|name| ["id","created_at","updated_at"].include?(name)}
于 2012-10-11T04:01:27.857 回答
2

你也可以使用拒绝

a = [1,2,3]
a.reject{|x| x>=2}
=> [1]
于 2012-10-11T04:09:49.377 回答
2

Dup 可以提供帮助,但需要进行重组。dup 创建“浅拷贝”的事实,它具有以下不明显的后果:

> arr = Model.column_names.dup
=> ["id", "name", "klasse", "cars_count", "klasse_id"] 
> arr.delete('id')
=> "id" 
> arr
=> ["name", "klasse", "cars_count", "klasse_id"] 
> Model.column_names
=> ["id", "name", "klasse", "cars_count", "klasse_id"] 
> arr.each &:upcase!
=> ["NAME", "KLASSE", "CARS_COUNT", "KLASSE_ID"] 
> Model.column_names
=> ["id", "NAME", "KLASSE", "CARS_COUNT", "KLASSE_ID"] 
于 2012-10-11T05:23:53.007 回答