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

(Tuis.) #1
Hash

Dir | 47

Dir



  • Dir.[] is shorthand forDir.glob:
    Dir["/s*"] # => ["/scripts", "/srv", "/selinux", "/sys", "/sbin"]


Enumerable



  • Enumerable#all?returnstrueif the given block returns atruevalue for all items in the
    enumerable. Similarly,Enumerable#any?returnstrueif the block returns atruevalue
    for any item.
    (1..10).all?{|i| i > 0 && i < 15} # => true


(1..10).any?{|i| i*i == 9} # => true
(1..10).any?{|i| i*i == 8} # => false


  • Enumerable#grepfilters an enumerable against another object using===, affording all of
    the usual flexibility of the=== method:
    [1, 2, 3].methods.grep(/^so/) # => ["sort!", "sort", "sort_by"]


[1, :two, "three", 4].grep(Fixnum) # => [1, 4]


  • Enumerable#sort_bysorts the enumerable by the value of the given block, by perform-
    ing a Schwartzian transform*on the data. It builds up a set of input elements, each
    stored with the result of applying the block to that element. Because the block should
    return the same value when called with the same input, it only needs to be called once
    per input. Thus,O(n) calculations are done rather thanO(n lg n).
    However, thesort_bytechnique is counterproductive when key calculation is inexpen-
    sive; in such cases,Enumerable#sortshould be called with a custom comparison as a
    block.


File



  • File.join(*parts) is a platform-independent way to join path segments:
    File.join("..", "test.rb") # => "../test.rb"

  • File.open can take a block, which will automatically close the file when exited.


Hash



  • Hash.newaccepts a block, which provides a way to calculate a default value if the hash
    has none. This is useful for caching. The first time a cached method is called with a
    particular set of arguments, the block is invoked; it calculates the value and stores it
    in the hash for future access. ActiveSupport has an implementation of hash caching in
    caching_tools.rb, which generates hashes like this:
    Hash.new do |as, a|
    as[a] = Hash.new do |bs, b|



  • Named after Randal Schwartz, who popularized themap-sort-unmap technique in Perl.

Free download pdf