Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如果我键入c.messages.reverse.delete_at(0)没有任何反应,则消息是数组。如果我键入c.messages.delete_at(0)它会删除第一个元素。为什么这不适用于反向?
c.messages.reverse.delete_at(0)
c.messages.delete_at(0)
发生这种情况是因为reverse返回一个新数组,您正在删除其中的最后一个成员。您可以使用reverse!,它会改变原始数组。
reverse
reverse!
如果要从数组中删除最后一个元素,最好的方法是使用pop.
pop
>> arr = ["a", "b", "c"] => ["a", "b", "c"] >> arr.pop => "c" >> arr => ["a", "b"]
delete_at可以处理负索引,从数组末尾向后计数(-1 是最后一个元素):
delete_at
ar = [1,2,3,4,5] ar.delete_at(-2) p ar #=> [1, 2, 3, 5]