Ruby Shortcuts

April 10th, 2013 15:15 – by Torsten Trautwein

Symbol to_proc

Especially when chaining together methods like collect, select, map, etc. using the symbol as a shorthand for a block, can be very useful:

class Character
  attr_accessor :name, :actor

  def initialize(opts = {})
    @name, @actor = opts[:name], opts[:actor]
  end
end

jack = Character.new(name: 'Jack Shepard', actor: 'Matthew Fox')
kate = Character.new(name: 'Kate Austen', actor: 'Evangeline Lilly')
hurley = Character.new(name: 'Hugo Reyes', actor: 'Jorge Garcia')
sayid = Character.new(name: 'Sayid Jarrah', actor: 'Naveen Andrews')
sun = Character.new(name: 'Sun-Hwa Kwon', actor: 'Yunjin Kim')
aaron = Character.new(name: 'Aaron Littleton', actor: 'William Blanchette')

oceanic_six = [jack, kate, hurley, sayid, sun, aaron]

oceanic_six.collect { |c| c.name }.map{ |c| c.downcase }.last
=> "aaron littleton"

oceanic_six.collect(&:name).map(&:downcase).last
=> "aaron littleton"

Lambda

Since Ruby 1.9, you can use -> instead of lambda. This of course also holds true for arguments, though the syntax changes a little:

old_l = lambda { |x| x+19 }
new_l = -> x { x+19 }

old_l.call(23)
=> 42

new_l.call(23)
=> 42

Presence

The presence method is Rails specific, but nevertheless improves readability by a fair amount:

something = 'something'
anything = (something && something.present?) ? something : 'default'
=> "something"
anything = something.presence || 'default'
=> "something"

something = nil
anything = (something && something.present?) ? something : 'default'
=> "default"
anything = something.presence || 'default'
=> "default"

Back

Get In Touch

The usual channels

twitter @neowork
Google+ +neowork
github neowork
500px neowork
E-Mail mail@neowork.com

Or send a message right away

captcha

Imprint

Torsten Trautwein
Pfannmuellerstr. 28
60488 Frankfurt am Main, Germany

mail@neowork.com
+49 (0)7000 NEOWORK
+49 (0)7000 63 69 675
max. 0.12 €/min on German landlines