Skip to content

Instantly share code, notes, and snippets.

@Eugene-Shapovalov
Last active March 2, 2016 13:32
Show Gist options
  • Save Eugene-Shapovalov/2b1940a0ad5e59792374 to your computer and use it in GitHub Desktop.
Save Eugene-Shapovalov/2b1940a0ad5e59792374 to your computer and use it in GitHub Desktop.
Ruby examples
Array.new(10) { rand 300 } #=> [217, 232, 274, 141, 157, 180, 11, 193, 66, 187]
[].methods.grep /^re.*/ # => array of matched methods
# All to boolean
!!(4) # => true
!!(nil) # false
# Different ways to call a lambda
my_lambda = -> { puts 'Hello' }
my_lambda.call
my_lambda[]
my_lambda.()
my_lambda.===
# Extend class with method
module Rev
def rev
self.reverse
end
end
s = "abc123"
s.extend(Rev) # => :rev
s.rev # => "321cba"
# INCLUDE AND EXTEND THE RAILS PLUGIN WAY
module ActsAsCounter
# class method
def acts_as_lifeform
include InstanceMethods
end
module InstanceMethods
def count
counter++
save
end
end
end
ActiveRecord::Base.extend ActsAsCounter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment