English 中文(简体)
“delete_at” 删除的方法
原标题:"delete_at" Method Deletes Only Even Array Elements
  • 时间:2010-12-22 22:52:13
  •  标签:
  • arrays
  • ruby

为什么该法典只删除阵列中的内容? 我预计,每个数值从零到3,可乘以,每次删除每个要素。 但它只是删除了一条[0]和一条(2)。 我做了什么错误? 预收

a=%w(ant bat cat dog)
puts a.inspect #output: ["ant", "bat", "cat", "dog"]

for k in (0..3)
    a.delete_at(k)
end

puts a.inspect #output: ["bat", "dog"]

UPDATE--

感谢你的答复;我看到我现在所做的事情。 为了删除阵列的每一部分,阿雷拉方法的转变是适当的。 例如:

for each in (0..3)
    a.shift
    print a
end

这将把第一个要素从阵列中转移,并将随后的每个要素移至一个单元。 感谢你建议使用每种物品——我可以看到这是首选的辛迪加。

附录 2-

下面的法典部分是否更能代表适当的 rub。

(0..3).to_a.each do
    a.shift
    p a
end

而且 得益于关于删除阵列内容的建议。

最佳回答

因为删除要素0,即构成原阵列要素2。

Initially:
[ant, bat, cat, dog]

a.delete_at[0] => ant
[bat, cat, dog]

go to next element -> 1

a.delete_at[1] => cat
[bat, dog]

go to next element -> 2
a.delete_at[2] => nil (out of range)

go to next element -> 3
a.delete_at[3] => nil
问题回答

由于你正在删除现有的阵列,而执行过程第三次进入 lo,你的阵列低于k的价值。

处决过程

a=%w(ant bat cat dog)
puts a.inspect #output: ["ant", "bat", "cat", "dog"]

for k in (0..3).to_a
  p k
  a.delete_at(k)
  p a
end

puts a.inspect #output: ["bat", "dog"]

这里的产出

0
["bat", "cat", "dog"]
1
["bat", "dog"]
2
["bat", "dog"]
3
["bat", "dog"]

k2时,你试图删除索引<2>中的内容,但你的阵列仅由指数0和1的2个元组成。

PS。 避免使用<条码>。 使用<代码>each 相反,是“更加面向Ruby”。

诚然,Firas和Simone回答了你提出的问题,但是如果你真心想知道如何有效地删除,你就可以从一个阵列中删除所有内容:

a.clear

您可以删除一系列内容。

a.slice!(0..3)

在这两种情况下都不需要反复处理。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签