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)



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

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]



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

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)



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

def pick_index
  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]



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

def pick_index!
  i = pick_index
  delete_at i
  i
end

#pick_with_indexObject

Return a random element of self with its index. a = ["a", "b", "c", "d"] a.pick_with_index #=> ["b", 1] a #=> ["a", "b", "c", "d"]



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

def pick_with_index
  i = pick_index
  [self[i], i]
end

#pick_with_index!Object

Delete and return a random element of self with its index. a = ["a", "b", "c", "d"] a.pick_with_index! #=> ["b", 1] a #=> ["a", "c", "d"]



84
85
86
87
88
# File 'lib/rand.rb', line 84

def pick_with_index!
  rv = pick_with_index
  delete_at rv[1]
  rv
end

#shuffleObject

Return an array of the elements in random order. [11, 22, 33, 44].shuffle #=> [33, 11, 44, 22]



92
93
94
# File 'lib/rand.rb', line 92

def shuffle
  dup.shuffle!
end

#shuffle!Object

Destructive shuffle. Arrange the elements of self in new order. Using Fisher-Yates shuffle. a = [11, 22, 33, 44] a.shuffle! a #=> [33, 11, 44, 22]



101
102
103
104
105
106
107
108
109
110
# File 'lib/rand.rb', line 101

def shuffle!
  (size-1).downto(1) {|index|
    other_index = rand(index+1)
    next if index == other_index
    tmp = self[index]
    self[index] = self[other_index]
    self[other_index] = tmp
  }
  self
end