Last active
March 2, 2016 13:32
-
-
Save Eugene-Shapovalov/2b1940a0ad5e59792374 to your computer and use it in GitHub Desktop.
Ruby examples
This file contains hidden or 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
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