Class: Array

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

Instance Method Summary collapse

Instance Method Details

#to_sentence(method = :to_s) ⇒ Object

Convert an array to a nice sentence. Method is called on each element of the array, and should return a string.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/support/array.rb', line 3

def to_sentence(method = :to_s)
  case size
  when 0
    ''
  when 1
    first.send method
  when 2
    first.send(method) + ' and ' + last.send(method)
  else
    sentence = self[1..-2].inject(first.send(method)) do |sentence, element|
      sentence += ', ' + element.send(method)
    end
    sentence + ', and ' + last.send(method)
  end
end