Project

General

Profile

Actions

Feature #19987

closed

add sample method to Range

Added by horv77@protonmail.com (Andras Horvath) about 1 year ago. Updated about 1 year ago.

Status:
Feedback
Assignee:
-
Target version:
-
[ruby-core:115244]

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) about 1 year 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]
Actions #2

Updated by Anonymous about 1 year ago

Sounds logical, thank you.

Andras

Sent with Proton Mail secure email.

Updated by rubyFeedback (robert heiler) about 1 year 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) about 1 year 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) about 1 year 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]
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0