数组名存储在数组中,推送到数组 - 不按预期工作

时间:2015-10-20 23:37:13

标签: arrays ruby push

@board = {1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0, 8=>"b", 9=>"r", 10=>"u", 11=>"c", 12=>0, 13=>0, 14=>"d", 15=>"h", 16=>"s", 17=>"l", 18=>0, 19=>0, 20=>"o", 21=>"i", 22=>"l", 23=>"b", 24=>0, 25=>0, 26=>"g", 27=>"t", 28=>"f", 29=>"e", 30=>0, 31=>0, 32=>0, 33=>0, 34=>0, 35=>0, 36=>0}
@words = {"shift"=>[16, 15, 21, 28, 27], "bell"=>[23, 29, 22, 17], "curb"=>[11, 10, 9, 8], "dog"=>[14, 20, 26]}

@col1 = [8, 14, 20, 26]
@col2 = [9, 15, 21, 27]
@col3 = [10, 16, 22, 28]
@col4 = [11, 17, 23, 29]

@rcol1 = Array.new
@rcol2 = Array.new
@rcol3 = Array.new
@rcol4 = Array.new

@cols = [@col1, @col2, @col3, @col4]
@rcols0 = [@rcol1, @rcol2, @rcol3, @rcol4]

out = @words["dog"]

 out.each do |remove|
  @board[remove] = 100
 end

def colclone
  nums = 0
  @rcols0.each do |fixy|
    a = @cols[nums]
    a.each do |stick|
      fixy[nums].push @board[stick]
    end
    nums += 1
  end
end

这是实际的代码。我试图简化,但我认为我必须遗漏一些东西。

我正在玩棋盘游戏。我想要的是

--> @rcol1 = [0, 1, 2, 3]

我得到的是我的参考数组中的结果

--> @rcols0 = [[0, 1, 2, 3], ...]

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:1)

你对它的运作方式有错误的想法或错误的词汇。 names不存储数组的名称。 names存储对Array对象的引用。它们的名字并不重要。

array1 = [0, 1, 2]
array2 = [10,20,30]
names = [array1, array2]

# names[1] contains a reference to array2
# So this is the same as array2[2]
puts names[1][2]   # 30

您的代码运行正常。

names.each do |update|
  update.push 3
  update.push 4
end

puts array1.inspect # [0, 1, 2, 3, 4]

答案 1 :(得分:0)

您的解决方案似乎有效:

array1 = [1,2,3]
 => [1, 2, 3] 

array2 = [4,5,6]
 => [4, 5, 6] 

names = [array1, array2]
 => [[1, 2, 3], [4, 5, 6]] 

names.each do |update|
  update.push 8
  update.push 9
end
 => [[1, 2, 3, 8, 9], [4, 5, 6, 8, 9]] 

array1
 => [1, 2, 3, 8, 9] 

array2
 => [4, 5, 6, 8, 9] 

答案 2 :(得分:0)

我认为你正在寻找的是这样的东西:

array1 = [0, 1, 2]
array2 = [10, 11, 12]
array3 = [20, 21, 22]

names = [array1, array2, array3]

names.each do |array|
    i = array[array.length-1] + 1
    array.push(i,i+1)
end

p array1
p array2
p array3
p names

以上输出为:

[0, 1, 2, 3, 4]      #array1
[10, 11, 12 ,13, 14] #array2       
[20, 21, 22, 23, 24] #array3
[[0, 1, 2, 3, 4], [10, 11, 12, 13, 14], [20, 21, 22, 23, 24]] #names array

修改和/或扩展代码以满足您的需求。