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

(Tuis.) #1

Symbol#to_proc


74 | Chapter 2: ActiveSupport and RailTies


Miscellaneous methods core_ext/string/access.rb,core_ext/string/conversions.rb,
core_ext/string/starts_ends_with.rb



  • String#at(position)returns the character at the specified position. This is an easy way
    around the fact that Ruby’sString#[]returns a character code rather than a string in
    Ruby 1.8:
    "asdf"[0] # => 97
    "asdf"[0] == ?a # => true
    "asdf".at(0) # => "a"

  • String#from,String#to,String#first, andString#lastwork just as their names sug-
    gest. As usual, negative indices count from the end of the string:
    "asdf".from(1) # => "sdf"
    "asdf".to(1) # => "as"
    "asdf".from(1).to(-2) # => "sd"


"asdf".first # => "a"
"asdf".last # => "f"
"asdf".first(2) # => "as"
"asdf".last(2) # => "df"


  • String#to_time(defaults to UTC),String#to_time(:local), andString#to_dateare
    easy ways to delegate toParseDate:
    "1/4/2007".to_date.to_s # => "2007-01-04"


"1/4/2007 2:56 PM".to_time(:local).to_s # => "Thu Jan 04 14:56:00 CST 2007"


  • String#starts_with?(prefix) andString#ends_with?(suffix)test whether a string
    starts with or ends with another string.
    "aoeu".starts_with?("ao") # => true
    "aoeu".starts_with?("A") # => false
    "aoeu".ends_with?("eu") # => true
    "aoeu".ends_with?("foo") # => false


Symbol#to_proc symbol.rb


ActiveSupport defines only one extension toSymbol, but it is a powerful one: the ability to
convert a symbol to aProcusingSymbol#to_proc. This idiom is used all over Rails now.
Code such as this:
(1..5).map {|i| i.to_s } # => ["1", "2", "3", "4", "5"]


becomes this, usingSymbol#to_proc:


(1..5).map(&:to_s) # => ["1", "2", "3", "4", "5"]

The&symbol tells Ruby to treat the symbol:to_sas a block argument; Ruby knows that
the argument should be aProcand tries to coerce it by calling itsto_procmethod. Active-
Support supplies aSymbol#to_procmethod that returns just such aProc; when called, it
invokes the specified method on its first argument.

Free download pdf