Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Array

Array | 61

they are extremely useful during the process of building a Rails application. The core
extensions are low-level utility methods for Ruby; they do not make the impossible
possible, but they do help to simplify application code.


Array


Conversions core_ext/array/conversions.rb



  • Array#to_sentence joins the array’s elements and converts to a string:
    %w(Larry Curly Moe).to_sentence # => "Larry, Curly, and Moe"

  • Array#to_s(:db) collects an array of ActiveRecord objects (or other objects that
    respond to theid method) into a SQL-friendly string.

  • Array#to_xmlconverts an array of ActiveRecord objects into XML. This is usually used
    to implement REST-style web services. It relies on the contained objects’ implementa-
    tion ofto_xml (such asActiveRecord::XmlSerialization.to_xml).
    render :xml => Product.find(:all).to_xml
    Note thatrender(:xml => ...)andrender(:json => ...)are new synonyms for
    render(:text => ...) that change the response’s MIME type appropriately.


Grouping core_ext/array/grouping.rb



  • Array#in_groups_of(size, fill_with) groups elements of an array into fixed-size groups:
    (1..8).to_a.in_groups_of(3) # => [[1, 2, 3], [4, 5, 6], [7, 8, nil]]
    (1..8).to_a.in_groups_of(3, 0) # => [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
    (1..8).to_a.in_groups_of(3, false) # => [[1, 2, 3], [4, 5, 6], [7, 8]]

  • Array#split splits an array on a value or the result of a block:
    (1..8).to_a.split(4) # => [[1, 2, 3], [5, 6, 7, 8]]
    (1..8).to_a.split {|i| i == 2} # => [[1], [3, 4, 5, 6, 7, 8]]


Option processing core_ext/array/extract_options.rb



  • Array#extract_options!removes and returns the last array item if it is a hash; other-
    wise, it returns an empty hash. This supports the common pattern of using a hash as
    the last argument to provide keyword arguments to a method:
    def example(*args)
    options = args.extract_options!
    "#{args.inspect} :: #{options.inspect}"
    end


example 1 # => "[1] :: {}"
example 1, 2 # => "[1, 2] :: {}"
example 1, 2, :a => 3 # => "[1, 2] :: {:a=>3}"

Random selection core_ext/array/random_access.rb



  • Array#rand returns an element selected at random from the array:
    (1..10).map{ (1..10).to_a.rand } # => [2, 7, 7, 7, 7, 1, 10, 10, 2, 5]

Free download pdf