Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/gamefic/core_ext/array.rb

Instance Method Summary collapse

Instance Method Details

#join_and(sep = ', ', and_sep = ' and ', serial = true) ⇒ String

Get a string representation of the array that separates elements with commas and adds a conjunction before the last element.

Examples:

animals = ['a dog', 'a cat', 'a mouse']
animals.join_and #=> 'a dog, a cat, and a mouse'

Parameters:

  • sep (String) (defaults to: ', ')

    The separator for all but the last element

  • andSep (String)

    The separator for the last element

  • serial (Boolean) (defaults to: true)

    Use serial separators (e.g., serial commas)

Returns:



53
54
55
56
57
58
59
60
# File 'lib/gamefic/core_ext/array.rb', line 53

def join_and(sep = ', ', and_sep = ' and ', serial = true)
  if length < 3
    join(and_sep)
  else
    start = self[0..-2]
    start.join(sep) + "#{serial ? sep.strip : ''}#{and_sep}#{last}"
  end
end

#join_or(sep = ', ', or_sep = ' or ', serial = true) ⇒ String

Returns:

See Also:



65
66
67
# File 'lib/gamefic/core_ext/array.rb', line 65

def join_or(sep = ', ', or_sep = ' or ', serial = true)
  join_and(sep, or_sep, serial)
end

#pop_sampleObject

Pop a random element from the array.



38
39
40
# File 'lib/gamefic/core_ext/array.rb', line 38

def pop_sample
  delete_at(rand(length))
end

#that_are(*cls) ⇒ Array

Get a subset of the array that matches the arguments. If the argument is a Class or Module, the elements must be of the type. If the argument is a Symbol, it should be a method for which the elements must return true. If the argument is an Object, the elements must equal the object.

Examples:

animals = ['dog', 'cat', nil]
animals.that_are(String) #=> ['dog', 'cat']
animals.that_are('dog')  #=> ['dog']
animals.that_are(:nil?)  #=> [nil]

Returns:



16
17
18
19
20
21
22
# File 'lib/gamefic/core_ext/array.rb', line 16

def that_are(*cls)
  result = dup
  cls.each do |c|
    _keep result, c, true
  end
  result
end

#that_are_not(*cls) ⇒ Array

Get a subset of the array that does not match the arguments. See Array#that_are for information about how arguments are evaluated.

Returns:



28
29
30
31
32
33
34
# File 'lib/gamefic/core_ext/array.rb', line 28

def that_are_not(*cls)
  result = dup
  cls.each do |c|
    _keep result, c, false
  end
  result
end