从数组中删除时删除Column_names

时间:2012-10-11 03:53:49

标签: ruby-on-rails ruby

如果我这样做:

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

Model.column_names命令将返回不包含idcreated_at&的数组。 updated_at列名称。我推测name_array会删除名称,而不是Model.column_names数组。

Rails 3.0.13 Ruby 1.9.3

3 个答案:

答案 0 :(得分:5)

请参阅delete_if的{​​{3}}:

  

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

因此,当您从name_array删除元素时,实际上是从Model.column_names删除它们,因为它们指的是同一个东西。

如果您不想这样做,请在删除之前Array documentation

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

答案 1 :(得分:2)

你也可以使用拒绝

a = [1,2,3]
a.reject{|x| x>=2}
=> [1]

答案 2 :(得分: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"]