Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/rand.rb

Instance Method Summary collapse

Instance Method Details

#pickObject

Choose and return a random element of self.

[1, 2, 3, 4].pick  #=> 2 (or 1, 3, 4)


40
41
42
# File 'lib/rand.rb', line 40

def pick
  self[pick_index]
end

#pick!Object

Deletes a random element of self, returning that element.

a = [1, 2, 3, 4]
a.pick  #=> 2
a       #=> [1, 3, 4]


48
49
50
51
52
53
# File 'lib/rand.rb', line 48

def pick!
  i = pick_index
  rv = self[i]
  delete_at(i)
  rv
end

#pick_indexObject

Return the index of an random element of self.

["foo", "bar", "baz"].pick_index  #=> 1 (or 0, or 2)


57
58
59
# File 'lib/rand.rb', line 57

def pick_index
  Kernel.rand(size)
end

#pick_index!Object

Destructive pick_index. Delete a random element of self and return its index.

a = [11, 22, 33, 44]
a.pick_index!  #=> 2
a              #=> [11, 22, 44]


66
67
68
69
70
# File 'lib/rand.rb', line 66

def pick_index!
  i = pick_index
  delete_at i
  i
end

#shuffleObject

Return an array of the elements in random order.

[11, 22, 33, 44].shuffle  #=> [33, 11, 44, 22]


74
75
76
# File 'lib/rand.rb', line 74

def shuffle
  sort_by{rand}
end

#shuffle!Object

Destructive shuffle. Arrange the elements of self in new order.

a = [11, 22, 33, 44]
a.shuffle!
a                      #=> [33, 11, 44, 22]


82
83
84
# File 'lib/rand.rb', line 82

def shuffle!
  sort!{rand <=> 0.5}
end