每次使用Ruby调用时,数组都可以输出不同的值吗?

时间:2011-10-14 10:42:12

标签: ruby arrays

如果我的数组类似于

   greetings = ["Hello", "Goodbye", "Hi", "Bye"]

每次调用数组都可以输出不同的值吗?

4 个答案:

答案 0 :(得分:5)

Ruby 1.8:greetings.choiceArray#choice

Ruby 1.9:greetings.sampleArray#sample

答案 1 :(得分:4)

greetings[rand(greetings.size)]

答案 2 :(得分:2)

我认为greetings.shuffle.pop更具可读性: - )

user     system      total        real
sahil  0.000000   0.010000   0.010000 (  0.115553)
chrispanda  0.000000   0.000000   0.000000 (  0.000154)
tokland  0.000000   0.000000   0.000000 (  0.000008)

@ tokland's更整洁,效率更高

答案 3 :(得分:0)

greetings = ["Hello", "Goodbye", "Hi", "Bye"]
greeter = greetings.cycle


puts greeter.next
# do something else
5.times{ puts greeter.next}