Class: Array
Direct Known Subclasses
Instance Method Summary collapse
-
#only?(value) ⇒ Boolean
Whether the array contains a single element and that element is equal to a given value to @==@) to value and false otherwise.
-
#sample(n = 1) ⇒ <Object>, Object
Choose a random element or n random elements.
-
#to_array ⇒ Array
Override of Object#to_array.
-
#to_h(pairs = true) ⇒ Hash
Converts an array to a hash.
Instance Method Details
#only?(value) ⇒ Boolean
Whether the array contains a single element and that element is equal to a given value to @==@) to value and false otherwise.
197 198 199 |
# File 'lib/ruber/utils.rb', line 197 def only? value self.size == 1 and self[0] == value end |
#sample(n = 1) ⇒ <Object>, Object
Choose a random element or n random elements
It’s a version for ruby 1.8.7 of Array#sample from ruby 1.9. It uses Array#choice which only exists in ruby 1.8.7 but this doesn’t matter since this method is only defined in ruby 1.8.7
Note: ruby 1.9 already defines this method, so the original version is kept
is greater than one, then an array of n elements randomly chosen from those in the array are returned (without duplicates). If n is greater than the size of the array, then the returned array will have the size of the array
157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/ruber/utils.rb', line 157 def sample n = 1 if n == 1 then choice else a = dup n = [a.size, n].min res = [] n.times do res << a.delete(rand(a.size)) end res end end |
#to_array ⇒ Array
Override of Object#to_array
137 138 139 |
# File 'lib/ruber/utils.rb', line 137 def to_array self end |
#to_h(pairs = true) ⇒ Hash
Converts an array to a hash
Depending on the value of the argument, this method can work as the reverse of @Hash#to_a@ or as @Hash.[]@.
In the first case, each element of the array must be an array of size 2. The first element of each inner array will be used as key, while the second will be used as the corresponding value.
In the second case, this method works exactly as @Hash.[]@
185 186 187 188 189 |
# File 'lib/ruber/utils.rb', line 185 def to_h pairs = true if pairs then self.inject({}){|res, i| res[i[0]] = i[1]; res} else Hash[*self] end end |