Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a random item from an array in ruby (not rails) [duplicate]

Tags:

People also ask

How do you select a random element from an array in Ruby?

Just use Array#sample : [:foo, :bar]. sample # => :foo, or :bar :-) It is available in Ruby 1.9.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

What does .select do in Ruby?

Ruby | Array select() function Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.


I have an array of countries:

@countries = ["Canada", "Denmark", "Germany", "Isle of Man", "Namibia", "Qatar", "South Africa",  "United Kingdom","United States"]

And am building some random data for testing like this:

@test = [{ :name   => "AAA -"+Faker::Name.name,  :country => @countries.???? ....}]

How do I get a random value from the @countries hash?

@countries.rand(mlen)

does not work and returns NoMethodError: private methodrand' called for #`.