Feature #19987
closedadd sample method to Range
Description
Dear Devs, I'd like to suggest a change. Since the following works:
(1..99).first(5)
Therefore this one could be logical and useful to work:
(1..99).sample(5)
Thanks,
Andras
Updated by ufuk (Ufuk Kayserilioglu) almost 2 years ago
The first call works because Range is an Enumerable, and since getting the first element is an act of enumeration. On the other hand, sample needs to know the full list to do what it is doing, so can't be seen as an act of enumeration.
For example, first would work with an unbounded enumerable, but there is no way sample could:
(1..).first(5)
# => [1, 2, 3, 4, 5]
Updated by Anonymous almost 2 years ago
Sounds logical, thank you.
Andras
Sent with Proton Mail secure email.
Updated by rubyFeedback (robert heiler) almost 2 years ago
I think conceptually .first() is not the same as .sample(). At the least when I read
it, I would assume that .first() yields the first five elements (if the argument is
5), whereas .sample() should probably return 5 random elements. Not sure if others
read it the same way, but that was my initial impression.
Updated by nobu (Nobuyoshi Nakada) almost 2 years ago
- Status changed from Open to Feedback
Even if limited to bound Range, we can't enumerate all possible elements in Float.
As in the first proposal, it would make sense only for Integer ranges.
May we close this?
Updated by nobu (Nobuyoshi Nakada) almost 2 years ago
Maybe what you want is Random#rand with a Range?
r = Random.new
5.times.map {r.rand(0..99)} #=> [83, 63, 43, 70, 90]