如果我的数组类似于
greetings = ["Hello", "Goodbye", "Hi", "Bye"]
每次调用数组都可以输出不同的值吗?
答案 0 :(得分:5)
Ruby 1.8:greetings.choice
(Array#choice)
Ruby 1.9:greetings.sample
(Array#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}