Method: Array#to_series

Defined in:
lib/jinx/helpers/array.rb

#to_series(conjunction = nil) ⇒ Object

Prints the content of this array as a series, e.g.:

[1, 2, 3].to_series #=> "1, 2 and 3"
[1, 2, 3].to_series('or') #=> "1, 2 or 3"

If a block is given to this method, then the block is applied before the series is formed, e.g.:

[1, 2, 3].to_series { |n| n + 1 } #=> "2, 3 and 4"


48
49
50
51
52
53
54
# File 'lib/jinx/helpers/array.rb', line 48

def to_series(conjunction=nil)
  conjunction ||= 'and'
  return map { |item| yield item }.to_series(conjunction) if block_given?
  padded_conjunction = " #{conjunction} "
  # join all but the last item as a comma-separated list and append the conjunction and last item
  length < 2 ? to_s : self[0...-1].join(', ') + padded_conjunction + last.to_s
end