Skip to content

Instantly share code, notes, and snippets.

@gunn
Created December 10, 2010 01:51
Show Gist options
  • Save gunn/735640 to your computer and use it in GitHub Desktop.
Save gunn/735640 to your computer and use it in GitHub Desktop.
Some common but neat ruby tricks
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
class Array
def sum
inject :+
end
def product
inject :*
end
end
class Fixnum
def f!
(1..self).to_a.product
end
terms = {:minute => 60, :hour => 3600, :day => 86400}
terms.each do |term, length|
define_method term do
self*length
end
alias_method "#{term}s", term
end
def ago
Time.now - self
end
end
puts (2.days+25.minutes).ago
puts 5.f!
puts [1, 2, 3, 4].product
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment