Ruby sample array method
In ruby programming language, sample() method of array are used to get single and multiple random elements of array. This method selects a random element by index, so that the index element is not repeated. Syntax of this method as follows.
Syntax : --------- ⓐ Array.sample ┐ ├──➝ return nil or single value Array.sample() ┘ ⓑ Array.sample(n) ➝ return new array ⇡ (Number of element) # Optional parameter Array.sample(n, random: rng) ➝ return new array Array.sample(random: rng) → obj
There is more than one variant of this method, Array.sample method are return single random element, If array is empty then this method return nil value.
When provide parameters of this method it indicates select number of unique elements. This method are return new array which contains unique index elements.
Ruby sample method example
In this section mention few examples which is useful to understand concept of sample() method. Let see an example to get the random element in array.
# Our array record = ["C","C++","Java","Ruby","Swift","Python"] # Test simple method v1 = record.sample() v2 = record.sample(3) # Display given record print(" Given record ",record) # Display random elements print("\n v1 : ",v1) print("\n v2 : ",v2)
Given record ["C", "C++", "Java", "Ruby", "Swift", "Python"] v1 : Python v2 : ["Python", "C++", "Swift"]
In above example are suitable when array not empty and given parameter value is less than size of array. What is occur when array contains duplicate elements. Let see an example.
# Our array record = [[1,2],4,[1,2],5,[1,2],4] # Test simple method v1 = record.sample() v2 = record.sample(4) # Display given record print(" Given record ",record) # Display random elements print("\n v1 : ",v1) print("\n v2 : ",v2)
Given record [[1, 2], 4, [1, 2], 5, [1, 2], 4] v1 : [1, 2] v2 : 4, [[1, 2], [1, 2], 4]
In above example understand following points.
(1) : This method is return a new resultant array which elements are distinct by array index.
(2) : If array element contains object, Then result array are share this object (such as class object, array, hash etc).
(3) : Result are this method always not same, Because it's select random element.
(4) : Element value may be the same if the element is duplicated.
Ruby sample method default nature
In this section mentioning its default behavior of sample() method. Which is describe, What is occurs when array empty, and what is occurs when parameter value more than size of array etc.
# Our array arr1 =  arr2 = [1,2,1] # Test simple method v1 = arr1.sample() # When value is more than array v2 = arr2.sample(8) # Display given array print(" Given arr1 ",arr1) print("\n Given arr2 ",arr2) # Display result elements print("\n v1 : ",v1) print("\n v2 : ",v2)
Given arr1  Given arr2 [1, 2, 1] v1 : v2 : [1, 1, 2]
When parameter value is more than size this method are return new array which include n array elements. And the resulting sequence is random.