Ruby:从数组中删除变量

时间:2015-06-17 19:38:08

标签: arrays ruby variables methods

新手在这里。提前谢谢。

这里的想法类似于从一副纸牌中随意拉一张牌。我想永久地从数组中拉出一个随机数。

我的代码给了我一个关于删除的错误!'方法。 "未定义的方法delete!' for [1, 2, 3, 4, 5, 6, 7, 8]:Array (repl):6:in初始化'"。但据我所知,这里可能有六个错误。

我已经对下面的代码进行了评论,因此您可以按照我的业余思维过程进行操作。我确定有一些很棒的方法可以用两行代码来编写这些代码,这些代码我还没有经历过。你能帮忙吗?

array = [1, 2, 3, 4, 5, 6, 7, 8]
# Create array of sequential numbers

high_number = array.length - 1
# Determining length of array for next line, offset by 1 for array

rand_number = rand(0..high_number)
# Create a random number from 0 (first array position) through high num

draw = array[rand_number]
# drawing that position number from array (passed on to another action)

array.delete!(rand_number)
# make sure the next time I loop through this array that number can't be drawn again

4 个答案:

答案 0 :(得分:2)

数组没有Date AM JL 25/06/2015 2500 300 24/06/2015 2300 1300 方法。也许你的意思是delete

  

删除(obj)→item或nil

     

从self中删除所有等于obj的项目。

     

返回上次删除的项目,如果找不到匹配的项目,则返回nil。

     

如果给出了可选代码块,如果找不到该项,则返回该块的结果。 (要删除nil元素并获取信息性返回值,请使用#compact!)

delete!

或者,从您使用它的方式来判断,也许您真的意味着delete_at

  

delete_at(index)→obj或nil

     

删除指定索引处的元素,返回该元素或   如果指数超出范围,则为零。

     

另见#slice!

a = [ "a", "b", "b", "b", "c" ]
a.delete("b")                   #=> "b"
a                               #=> ["a", "c"]
a.delete("z")                   #=> nil
a.delete("z") { "not found" }   #=> "not found"

您可能也有兴趣查看有关Array的其他一些方法,例如a = ["ant", "bat", "cat", "dog"] a.delete_at(2) #=> "cat" a #=> ["ant", "bat", "dog"] a.delete_at(99) #=> nil shufflesample。完整文档可在ruby-doc.org上找到。

答案 1 :(得分:0)

如果您要删除该项目,只是为了确保它不会再次绘制 Array#sample是一种可能性

body {
line-height: 1;
}

阵列保持不变。

答案 2 :(得分:0)

正如Ajedi32所说,请查看shufflepop,了解各种数组方法。

然后您可以将代码重写为:

array = (1..8).to_a
# Create array of sequential numbers

draw = array.shuffle!.pop
# randomize order of array in place, remove and return last element

答案 3 :(得分:0)

>> a = (1..8).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8]
>> b = a.delete(a.sample)
=> 6
>> a
=> [1, 2, 3, 4, 5, 7, 8]
>> b
=> 6
相关问题