Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/rdf/rdfxml/patches/array_hacks.rb
Instance Method Summary collapse
-
#permute(prefixed = []) ⇒ Object
wiki.rubygarden.org/Ruby/page/show/ArrayPermute Permute an array, and call a block for each permutation Author: Paul Battley.
-
#to_sentence(options = {}) ⇒ Object
Converts the array to a comma-separated sentence where the last element is joined by the connector word.
Instance Method Details
#permute(prefixed = []) ⇒ Object
wiki.rubygarden.org/Ruby/page/show/ArrayPermute Permute an array, and call a block for each permutation Author: Paul Battley
5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/rdf/rdfxml/patches/array_hacks.rb', line 5 def permute(prefixed=[]) if (length < 2) # there are no elements left to permute yield(prefixed + self) else # recursively permute the remaining elements each_with_index do |e, i| (self[0,i]+self[(i+1)..-1]).permute(prefixed+[e]) { |a| yield a } end end end |
#to_sentence(options = {}) ⇒ Object
Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:
-
:words_connector
- The sign or word used to join the elements in arrays with two or more elements (default: “, ”) -
:two_words_connector
- The sign or word used to join the elements in arrays with two elements (default: “ and ”) -
:last_word_connector
- The sign or word used to join the last element in arrays with three or more elements (default: “, and ”)
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/rdf/rdfxml/patches/array_hacks.rb', line 21 def to_sentence( = {}) default_words_connector = ", " default_two_words_connector = " and " default_last_word_connector = ", and " # Try to emulate to_senteces previous to 2.3 if .has_key?(:connector) || .has_key?(:skip_last_comma) ::ActiveSupport::Deprecation.warn(":connector has been deprecated. Use :words_connector instead", caller) if .has_key? :connector ::ActiveSupport::Deprecation.warn(":skip_last_comma has been deprecated. Use :last_word_connector instead", caller) if .has_key? :skip_last_comma skip_last_comma = .delete :skip_last_comma if connector = .delete(:connector) [:last_word_connector] ||= skip_last_comma ? connector : ", #{connector}" else [:last_word_connector] ||= skip_last_comma ? default_two_words_connector : default_last_word_connector end end # options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) = {:words_connector => default_words_connector, :two_words_connector => default_two_words_connector, :last_word_connector => default_last_word_connector}.merge() case length when 0 "" when 1 self[0].to_s when 2 "#{self[0]}#{[:two_words_connector]}#{self[1]}" else "#{self[0...-1].join([:words_connector])}#{[:last_word_connector]}#{self[-1]}" end end |