Ruby Array Exercises: Pick number of random elements from a given array
Write a Ruby program to 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:
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics