Module: Enumerable

Defined in:
lib/rbot/core/utils/extends.rb

Instance Method Summary collapse

Instance Method Details

#conjoin(*args, &block) ⇒ Object

This method is an advanced version of #join allowing fine control of separators:

[1,2,3].conjoin(', ', ' and ')
=> "1, 2 and 3

[1,2,3,4].conjoin{ |i, a, b| i % 2 == 0 ? '.' : '-' }
=> "1.2-3.4"

Code lifted from the ruby facets project: <facets.rubyforge.org> git-rev: c8b7395255b977d3c7de268ff563e3c5bc7f1441 file: lib/core/facets/array/conjoin.rb



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/rbot/core/utils/extends.rb', line 143

def conjoin(*args, &block)
  num = count - 1

  return first.to_s if num < 1

  sep = []

  if block_given?
    num.times do |i|
      sep << yield(i, *slice(i, 2))
    end
  else
    options = (Hash === args.last) ? args.pop : {}
    separator = args.shift || ""
    options[-1] = args.shift unless args.empty?

    sep = [separator] * num

    if options.key?(:last)
      options[-1] = options.delete(:last)
    end
    options[-1] ||= _(" and ")

    options.each{ |i, s| sep[i] = s }
  end

  zip(sep).join
end