Class: Array

Inherits:
Object show all
Defined in:
lib/ruber/utils.rb

Direct Known Subclasses

Ruber::OutputWidget::ActionList

Instance Method Summary (collapse)

Instance Method Details

- (Boolean) only?(value)

Whether the array contains a single element and that element is equal to a given value to ==) to value and false otherwise.

Parameters:

  • value (Object)

    the object to compare the only element of the array

Returns:

  • (Boolean)

    true if the array has size 1 and its element is equal (according



197
198
199
# File 'lib/ruber/utils.rb', line 197

def only? value
  self.size == 1 and self[0] == value
end

- (<Object>, Object) sample(n = 1)

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

Parameters:

  • n (Integer) (defaults to: 1)

    the number of elements to sample

Returns:

  • (<Object>, Object)

    if n is 1, then a single element is returned. If n



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

- (Array) to_array

Override of Object#to_array

Returns:



137
138
139
# File 'lib/ruber/utils.rb', line 137

def to_array
  self
end

- (Hash) to_h(pairs = true)

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.[]

Parameters:

  • pairs (Boolean) (defaults to: true)

    whether to work as the inverse of Hash#to_a or as Hash.[]

Returns:

  • (Hash)

    a hash built as described above



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