我想知道是否有人可以解释如何在Ruby中移动数组中的项目?
例如
array = [a,b,c,d,e,f,l]
然后成为
array = [b,c,d,e,f,a,l]
我想将“ a”移动到“ f”所在的位置,但是我不想切换它们。我想将“ a”移至该位置并使其具有“ f”,然后将其全部向下移动到数组中,而将诸如“ l”之类的在其之前的项目保留在原处。在这种特定情况下,不存在重复项。此外,无需保留原始数组的副本不变。
*已进行澄清
答案 0 :(得分:1)
您要插入位置6的“ l”之前。
array = ["a", "b" ,"c", "d", "e", "f", "l"]
array.insert(5,array.shift)
=> ["b" ,"c", "d", "e", "f", "a", "l"]
请注意,我们之所以指定位置5是因为一旦删除了第一个元素(array.shift
),新编号就会在位置5(以前是位置6)中带有“ l”。
如果您是在单独的步骤中执行此操作...
array = ["a", "b" ,"c", "d", "e", "f", "l"]
character_to_shift = array.shift # shift method removes and returns first entry in array
=> "a"
p array
=> ["b" ,"c", "d", "e", "f", "l"]
p.insert(5, character_to_shift) # insert inserts specified character at index position
=> ["b" ,"c", "d", "e", "f", "a", "l"]
答案 1 :(得分:0)
您可以通过从数组中删除'a'
并将其重新插入到'f'
+ 1的索引处来实现。请记住,下面的代码顺序很重要,因为索引会在删除项目。
array = %w[a b c d e f l]
deleted = array.delete('a') # returns nil if not found
index = array.index('f') # returns nil if not found
array.insert(index + 1, deleted)
#=> ["b", "c", "d", "e", "f", "a", "l"]
如果将其更改为单线,则会得到错误的结果。
array.insert(array.index('f') + 1, array.delete('a'))
#=> ["b", "c", "d", "e", "f", "l", "a"]
# ^ 'a' is placed one position to far
发生这种情况的原因是,执行顺序为 index ->(索引的添加)-> 删除-> 插入。可以通过删除+ 1
来解决此问题。但是,这仅考虑了'f'
之后出现'a'
的情况。
array = %w[f b c d e a l]
array.insert(array.index('f'), array.delete('a'))
#=> ["a", "f", "b", "c", "d", "e", "l"]
# ^ 'a' is placed before 'f' (+ 1 is needed here)
此外,如果未找到任何元素之一,则也会有问题,因为 index 或 delete 的结果可能是nil
。通过执行此多行操作,您可以通过及早返回方法来处理异常。
答案 2 :(得分:0)
这可以解决您的要求:
“第一个元素移至特定位置”
def move_first_element(a, x)
first = a.shift
a.insert(x, first)
end
如果运行此命令:
(0..6).each do |i|
a = [0,1,2,3,4,5,6]
move_first_element(a, i)
puts "First element to index: #{i}"
puts "#{a}"
end
结果是:
First element to index: 0
[0, 1, 2, 3, 4, 5, 6]
First element to index: 1
[1, 0, 2, 3, 4, 5, 6]
First element to index: 2
[1, 2, 0, 3, 4, 5, 6]
First element to index: 3
[1, 2, 3, 0, 4, 5, 6]
First element to index: 4
[1, 2, 3, 4, 0, 5, 6]
First element to index: 5
[1, 2, 3, 4, 5, 0, 6]
First element to index: 6
[1, 2, 3, 4, 5, 6, 0]