1

我在 Ruby 中有一个如下所示的数组:

[ 0] "Red",
[ 1] "Green",
[ 2] "Blue",
[ 3] "Yellow",
[ 4] "Cyan",
[ 5] "Magenta",
[ 6] "Orange",
[ 7] "Purple",
[ 8] "Pink",
[ 9] "White",
[10] "Black"

我需要搜索黄色和紫色之间的值并重建数组,使其看起来像这样:

[ 0] "Red",
[ 1] "Green",
[ 2] "Blue",
[ 3] [[0] "Cyan",[1] "Magenta",[2] "Orange" ],
[ 4] "Cyan",
[ 5] "Magenta",
[ 6] "Orange",
[ 7] "Purple",
[ 8] "Pink",
[ 9] "White",
[10] "Black"

在 Ruby 中有一个简单的方法吗?

4

3 回答 3

3

将 Array#index 值传递给 Array#slice

如果要按单元格的值而不是索引位置对数组进行切片,可以将 Array#index 值作为参数传递给 Array#slice。例如:

colors = ["Red", "Green", "Blue", "Yellow", "Cyan", "Magenta", 
          "Orange", "Purple", "Pink", "White", "Black"]

colors.slice colors.index('Yellow'), colors.index('Purple')
# => ["Yellow", "Cyan", "Magenta", "Orange", "Purple", "Pink", "White"]
于 2012-09-03T20:50:17.853 回答
2
ar = %w(red green blue yellow cyan magenta orange purple pink white black)
i = ar.index('yellow')
ar[i] = ar[i+1 ... ar.index('purple')]
p ar #=> ["red", "green", "blue", ["cyan", "magenta", "orange"], "cyan", "magenta", "orange", "purple", "pink", "white", "black"]
于 2012-09-03T20:52:15.417 回答
0

关键是通过数组的索引助手获取起点和终点,并在它之间获取数组并将其替换为起始位置

def rearrange arr,from,to
  sidx = arr.index from
  eidx = arr.index to
  arr[sidx] = arr[sidx+1..eidx]
end

arr= ["Red", "Green", "Blue", "Yellow", "Cyan", "Magenta", "Orange", "Purple", "Pink", "White", "Black"]
start = "Yellow"
stop = "Orange"

puts arr.inspect
#=> ["Red", "Green", "Blue", "Yellow", "Cyan", "Magenta", "Orange", "Purple", "Pink", "White", "Black"]
rearrange arr,start,stop
puts arr.inspect
#=> ["Red", "Green", "Blue", ["Cyan", "Magenta", "Orange"], "Cyan", "Magenta", "Orange", "Purple", "Pink", "White", "Black"]
于 2012-09-03T20:55:09.183 回答