class Array
def self.wrap(object)
Array("foo\nbar") # => ["foo\n", "bar"], in Ruby 1.8
Array.wrap(:foo => :bar) # => [{:foo => :bar}]
Array(:foo => :bar) # => [[:foo, :bar]]
the argument:
It differs with Array() in that it does not call +to_a+ on
object to an Array using #to_ary if it implements that.
Wraps the object in an Array unless it's an Array. Converts the
def self.wrap(object) if object.nil? [] elsif object.respond_to?(:to_ary) object.to_ary else [object] end end
def as_json(options = nil) self end #:nodoc:
def as_json(options = nil) self end #:nodoc:
def encode_json(encoder) "[#{map { |v| encoder.encode(v) } * ','}]" end #:nodoc:
:nodoc:
def encode_json(encoder) "[#{map { |v| encoder.encode(v) } * ','}]" end #:nodoc:
def extract_options!
options(1, 2) # => {}
end
args.extract_options!
def options(*args)
element in the array if it's a hash, otherwise returns a blank hash.
Extracts options from a set of arguments. Removes and returns the last
def extract_options! if last.is_a?(Hash) && last.extractable_options? pop else {} end end
def fifth
def fifth self[4] end
def forty_two
def forty_two self[41] end
def fourth
def fourth self[3] end
def from(position)
%w( a b c d ).from(10) # => nil
%w( a b c d ).from(2) # => %w( c d )
%w( a b c d ).from(0) # => %w( a b c d )
Returns the tail of the array from +position+.
def from(position) self[position..-1] end
def in_groups(number, fill_with = nil)
["4", "5"]
["1", "2", "3"]
%w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
["6", "7", " "]
["4", "5", " "]
["1", "2", "3"]
%w(1 2 3 4 5 6 7).in_groups(3, ' ') {|group| p group}
["8", "9", "10", nil]
["5", "6", "7", nil]
["1", "2", "3", "4"]
%w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
remaining slots with +fill_with+ unless it is +false+.
Splits or iterates over the array in +number+ of groups, padding any
def in_groups(number, fill_with = nil) # size / number gives minor group size; # size % number gives how many objects need extra accommodation; # each group hold either division or division + 1 items. division = size / number modulo = size % number # create a new array avoiding dup groups = [] start = 0 number.times do |index| length = division + (modulo > 0 && modulo > index ? 1 : 0) padding = fill_with != false && modulo > 0 && length == division ? 1 : 0 groups << slice(start, length).concat([fill_with] * padding) start += length end if block_given? groups.each { |g| yield(g) } else groups end end
def in_groups_of(number, fill_with = nil)
["1", "2"]
%w(1 2 3).in_groups_of(2, false) {|group| p group}
["3", " "]
["1", "2"]
%w(1 2 3).in_groups_of(2, ' ') {|group| p group}
["7", nil, nil]
["4", "5", "6"]
["1", "2", "3"]
%w(1 2 3 4 5 6 7).in_groups_of(3) {|group| p group}
padding any remaining slots with +fill_with+ unless it is +false+.
Splits or iterates over the array in groups of size +number+,
def in_groups_of(number, fill_with = nil) if fill_with == false collection = self else # size % number gives how many extra we have; # subtracting from number gives how many to add; # modulo number ensures we don't add group of just fill. padding = (number - size % number) % number collection = dup.concat([fill_with] * padding) end if block_given? collection.each_slice(number) { |slice| yield(slice) } else groups = [] collection.each_slice(number) { |group| groups << group } groups end end
def sample(n=nil)
[].sample # => nil
[1,2,3,4,5,6].sample(3) # => [2, 4, 5]
[1,2,3,4,5,6].sample # => 4
If the array is empty and +n+ is nil, returns nil. if +n+ is passed, returns [].
Returns a random element or +n+ random elements from the array.
Backport of Array#sample based on Marc-Andre Lafortune's http://github.com/marcandre/backports/
def sample(n=nil) return self[Kernel.rand(size)] if n.nil? n = n.to_int rescue Exception => e raise TypeError, "Coercion error: #{n.inspect}.to_int => Integer failed:\n(#{e.message})" else raise TypeError, "Coercion error: obj.to_int did NOT return an Integer (was #{n.class})" unless n.kind_of? Integer raise ArgumentError, "negative array size" if n < 0 n = size if n > size result = Array.new(self) n.times do |i| r = i + Kernel.rand(size - i) result[i], result[r] = result[r], result[i] end result[n..size] = [] result end unless method_defined? :sample
def second
def second self[1] end
def split(value = nil)
[1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
or the result of an optional block.
Divides the array into one or more subarrays based on a delimiting +value+
def split(value = nil) using_block = block_given? inject([[]]) do |results, element| if (using_block && yield(element)) || (value == element) results << [] else results.last << element end results end end
def third
def third self[2] end
def to(position)
%w( a b c d ).to(10) # => %w( a b c d )
%w( a b c d ).to(2) # => %w( a b c )
%w( a b c d ).to(0) # => %w( a )
Returns the beginning of the array up to +position+.
def to(position) self[0..position] end
def to_formatted_s(format = :default)
output:
Adding in the :db argument as the format yields a prettier
Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post"
to_s on all elements and joining them:
Converts a collection of elements into a formatted string by calling
def to_formatted_s(format = :default) case format when :db if respond_to?(:empty?) && self.empty? "null" else collect { |element| element.id }.join(",") end else to_default_s end end
def to_param
Calls to_param on all its elements and joins the result with
def to_param collect { |e| e.to_param }.join '/' end
def to_query(key)
using the given +key+ as the param name.
Converts an array into a string suitable for use as a URL query string,
def to_query(key) prefix = "#{key}[]" collect { |value| value.to_query(prefix) }.join '&' end
def to_sentence(options = {})
* :two_words_connector - The sign or word used to join the elements in arrays with two elements (default: " and ")
* :words_connector - The sign or word used to join the elements in arrays with two or more elements (default: ", ")
Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:
def to_sentence(options = {}) if defined?(I18n) default_words_connector = I18n.translate(:'support.array.words_connector', :locale => options[:locale]) default_two_words_connector = I18n.translate(:'support.array.two_words_connector', :locale => options[:locale]) default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale]) else default_words_connector = ", " default_two_words_connector = " and " default_last_word_connector = ", and " end options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) options.reverse_merge! :words_connector => default_words_connector, :two_words_connector => default_two_words_connector, :last_word_connector => default_last_word_connector case length when 0 "" when 1 self[0].to_s when 2 "#{self[0]}#{options[:two_words_connector]}#{self[1]}" else "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}" end end
def to_xml(options = {})
Message.all.to_xml(:skip_types => true)
The +options+ hash is passed downwards:
singularized. You can change it with the :children option.
By default root children have as node name the one of the root
customer_with_no_projects.projects.to_xml(:root => "projects")
To ensure a meaningful root element use the :root option:
[].to_xml
If the collection is empty the root element is "nil-classes" by default:
[{:foo => 1, :bar => 2}, {:baz => 3}].to_xml
Otherwise the root element is "records":
...
...
customer.projects.to_xml
if all elements belong to the same type and that's not Hash:
The root node reflects the class name of the first element in plural
not an exception is raised.
All elements are expected to respond to +to_xml+, if any of them does
in XML to this method.
to each element. Active Record collections delegate their representation
Returns a string that represents this array in XML by sending +to_xml+
def to_xml(options = {}) require 'active_support/builder' unless defined?(Builder) options = options.dup options[:indent] ||= 2 options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) options[:root] ||= if first.class.to_s != "Hash" && all? { |e| e.is_a?(first.class) } underscored = ActiveSupport::Inflector.underscore(first.class.name) ActiveSupport::Inflector.pluralize(underscored).tr('/', '_') else "objects" end builder = options[:builder] builder.instruct! unless options.delete(:skip_instruct) root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options) children = options.delete(:children) || root.singularize attributes = options[:skip_types] ? {} : {:type => "array"} return builder.tag!(root, attributes) if empty? builder.__send__(:method_missing, root, attributes) do each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) } yield builder if block_given? end end
def uniq_by
#=> [1, 2]
[1, 2, 3, 4].uniq_by { |i| i.odd? }
Return an unique array based on the criteria given as a proc.
def uniq_by hash, array = {}, [] each { |i| hash[yield(i)] ||= (array << i) } array end
def uniq_by!
def uniq_by! replace(uniq_by{ |i| yield(i) }) end