Created
December 10, 2010 01:51
-
-
Save gunn/735640 to your computer and use it in GitHub Desktop.
Some common but neat ruby tricks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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