From: Josh Cheek Date: 2012-06-26T23:50:39+09:00 Subject: Re: Array#sample is Set#sample and not Array#sample ! --0016e6d7e943b013fc04c361384a Content-Type: text/plain; charset=ISO-8859-1 On Mon, Jun 25, 2012 at 9:53 AM, Michel Demazure wrote: > Arrays are ordered, sets are not. Sampling an array should give random > elements in the good order. But : > > irb(main):001:0> (0..10).to_a.sample(5) > => [8, 10, 4, 6, 7] > > Today's Array#sample actually is Set#sample, but Set#sample does not > exist. > > irb(main):002:0> Set.new((0..10)).sample(5) > NoMethodError: undefined method `sample' for # 6, 7, 8, 9, 10}> > > Sample selects a random element from the array, so it makes sense that sample(5) takes 5 random elements from the array. It sounds like you're looking for take: [*0..10].take(5) # => [0, 1, 2, 3, 4] Or maybe take with random intervals? On Tue, Jun 26, 2012 at 4:48 AM, Lars Haugseth wrote: > I agree, sample isn't intended to work the way the OP suggests. > > There are other ways to achieve the desired effect: > > class Array > def ordered_sample(n) > values_at [*0...size].sample(n).sort > end > end > > a = [:a, :b, :c, :d, :e, :f, :g, :h] > > a.ordered_sample(4) > => [:b, :c, :d, :e] > a.ordered_sample(4) > => [:c, :d, :e, :h] > a.ordered_sample(4) > => [:a, :b, :c, :g] > > Maybe we're on different rubies, but I had to change the implementation to `values_at *[*0...size].sample(n).sort` --0016e6d7e943b013fc04c361384a Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
On Mon, Jun 25, 2012 at 9:53 AM, Michel Demazure <= ;lists@ruby-forum= .com> wrote:
Arrays are ordered, sets are not. Sampling an array should give random
elements in the good order. But :

irb(main):001:0> (0..10).to_a.sample(5)
=3D> [8, 10, 4, 6, 7]

Today's Array#sample actually is Set#sample, but Set#sample does not exist.

irb(main):002:0> Set.new((0..10)).sample(5)
NoMethodError: undefined method `sample' for #<Set: {0, 1, 2, 3, 4, = 5,
6, 7, 8, 9, 10}>


Sample selects a random element fro= m the array, so it makes sense that sample(5) takes 5 random elements from = the array.

It sounds like you're looking for take:
[*0..10].tak= e(5) # =3D> [0, 1, 2, 3, 4]

Or maybe take with = random intervals?

On Tue, Jun 26, 2012 at 4:= 48 AM, Lars Haugseth=A0<ruby-talk@larshaugseth.com>= =A0wrote:
I agree, samp= le isn't intended to work the way the OP suggests.

There are other ways to achieve the desired effect:

=A0class Arr= ay
=A0 =A0def ordered_sample(n)
=A0 =A0 =A0values_at [*0...size].samp= le(n).sort
=A0 =A0end
=A0end

=A0a =3D [:a, :b, :c, :d, :e, :f,= :g, :h]

=A0a.ordered_sample(4)
=A0=3D> [:b, :c, :d, :e]
=A0a.ordered_sample(4)
=A0=3D> [:c, :d= , :e, :h]
=A0a.ordered_sample(4)
=A0=3D> [:a, :b, :c, :g]

=A0
Maybe we're on different rubies, but I had to change the implement= ation to `values_at *[*0...size].sample(n).sort`
--0016e6d7e943b013fc04c361384a--