w3resource

Ruby Array Exercises: Pick number of random elements from a given array

Ruby Array: Exercise-3 with Solution

Write a Ruby program to pick number of random elements from a given array.

Ruby Array Exercises: Pick number of random elements from a given array

Ruby Code:

nums = [12, 34, 23, 56]
print "Original array:\n"
print nums
print "\n 2 random elements from the array.\n"
print nums.sample(2)
print "\n 3 random elements from the array.\n"
print nums.sample(3)

Output:

Original array:
[12, 34, 23, 56]
 2 random elements from the array.
[34, 12]
 3 random elements from the array.
[56, 12, 34]

Flowchart:

Flowchart: Pick number of random elements from a given array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check whether 7 appears as either the first or last element in a given array. The array length must be 1 or more.
Next: Write a Ruby program to check whether first and the last element are the same of a given array of integers. The array length must be 1 or more.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/ruby-exercises/array/ruby-array-exercise-3.php