获取范围之间的项目

时间:2012-09-03 20:33:16

标签: ruby arrays

我在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中有一种简单的方法吗?

3 个答案:

答案 0 :(得分:3)

将数组#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"]

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

答案 2 :(得分:0)

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

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"]