具有相似条目的Ruby数组

时间:2018-03-19 06:02:30

标签: arrays ruby

我有两个数组

Device = ["Washington DC","Newyork","San Diego","Florida"]

Device1 = ["Washington DC","Newyork","San Diego","Florida"]

当我这样做是为了从一个数组的元素中删除空格

Device.each do |x|
  x.gsub!(' ','')
  puts x
end

其他数组元素的空格也被删除了。当我为两个数组做出放置时,这就是我得到的

["WashingtonDC","Newyork","SanDiego","Florida"]
["WashingtonDC","Newyork","SanDiego","Florida"]

请告诉我我在做什么,或者我应该怎么做才能从一个数组元素中删除空格

2 个答案:

答案 0 :(得分:1)

很可能您的数组不包含不同的字符串,但引用到同一个字符串对象。当你修改一个,然后修改所有出现。

string = "a reference"
array_1 = [string]
array_2 = [string]

array_1[0].gsub!(" ", "")

puts array_1 #> areference
puts array_2 #> areference

这是因为您在两个数组中都引用了相同的字符串对象,并在其中修改它

puts array_1[0].object_id == array_2[0].object_id #> true

尝试以下内容以查看差异

string_1 = "now it works"
array_1 = [string_1]
string_2 = "now it works"
array_2 =[string_2]

array_1[0].gsub!(" ", "")
puts array_1 #> nowitworks
puts array_2 #> now it works

您还可以创建一个新数组并保留原始数组及其包含的对象:

array_1 = ["hey there"]
array_1_no_spaces = array_1.map do |string|
  string.gsub(" ", "") # just gsub, not gsub!
end

关于您的代码的说明:请遵循最佳做法并在较低的蛇案例中命名您的变量:

device
list_of_something
...

CamelCase样式用于类:

class Device
end

答案 1 :(得分:0)

如果您已将相同的value分配给不同的variables,如下所示:

device = ["Washington DC","Newyork","San Diego","Florida"]
device1 = ["Washington DC","Newyork","San Diego","Florida"]

然后您的代码绝对 正常

device.each do |x|
  x.gsub!(' ','')
  puts x
end

执行上述代码后,您的变量如下所示:

> device
#=> ["WashingtonDC", "Newyork", "SanDiego", "Florida"] 
> device1
#=> ["Washington DC", "Newyork", "San Diego", "Florida"]

<强> BUT

如果您通过variablevariable分配了一些值,那么每个变量都包含相同的对象。

> array = ["Washington DC","Newyork","San Diego","Florida"]
#=> ["Washington DC", "Newyork", "San Diego", "Florida"] 
> device = array
> device1 = array
> array.object_id
#=> 8031080 
> device.object_id
#=> 8031080 
> device1.object_id
#=> 8031080 

因此,当您对arraydevicedevice1等任何变量执行任何操作时,它都会反映所有变量。

您需要制作对象的副本。可以分配如下:

> array = ["Washington DC","Newyork","San Diego","Florida"]
> device = array.dup
> device1 = array.dup

> array.object_id
#=> 7077120 
> device.object_id
#=> 7005100 
> device1.object_id
#=> 6977660 

我希望现在这个简单的答案能让你清楚易懂。