aquaflamingo
aquaflamingo

Reputation: 822

How do I get random element from an Array in Crystal Lang?

If I have an array of elements, how do I get a random one from the collection?

For example:

my_array = [1,2,3,4,5,6,7,8]

# how to get a random value now?

Upvotes: 0

Views: 184

Answers (1)

aquaflamingo
aquaflamingo

Reputation: 822

Any collection that mixes in the Indexable module gains the ability to sample an element from it. Since an Array mixes in Indexable you can use the sample method for this purpose.

a = [1,2,3,4,5,6,7,8]
# 2
a.sample               
# 1
a.sample               
# 5
a.sample(Random.new(4))

Upvotes: 2

Related Questions