SlideShare a Scribd company logo
1 of 36
Download to read offline
Ruby Tips & Quirks #2
         Michał Łomnicki
      http://mlomnicki.com
Local variables
puts local_variables.inspect
y = 4
puts local_variables.inspect
Local variables
puts local_variables.inspect # => ["y"]
y = 4

puts local_variables.inspect # => ["y"]
Local variables
                 Ruby 1.8
puts local_variables.inspect # => ["y"]
y = 4
puts local_variables.inspect # => ["y"]
Local variables
                 Ruby 1.9
puts local_variables.inspect # => [:y]
y = 4
puts local_variables.inspect # => [:y]
String vs Symbol
class String
    unless instance_methods.include?("camelize")
        def camelize
            gsub(//(.?)/) { "::#{$1.upcase}" }
            .gsub(/(?:^|_)(.)/) { $1.upcase }
        end
    end
end
String vs Symbol
class String
    unless instance_methods.any? { |m| m.to_s == "camelize"
        def camelize
            gsub(//(.?)/) { "::#{$1.upcase}" }
            .gsub(/(?:^|_)(.)/) { $1.upcase }
        end
    end
end
String vs Symbol
class String
    unless instance_methods.method_defined?(:camelize)
        def camelize
            gsub(//(.?)/) { "::#{$1.upcase}" }
            .gsub(/(?:^|_)(.)/) { $1.upcase }
        end
    end
end
module functions
module Security
    def generate_password
        ('a'..'z').sample(8)
    end
end
class User
    include Security
end
User.new.generate_password
module functions
module Security
    def generate_password
        ('a'..'z').sample(8)
    end
end
module functions
module Security
    extend self
    def generate_password
        ('a'..'z').sample(8)
    end
end
module functions
module Security
    extend self
    def generate_password
        ('a'..'z').sample(8)
    end
end
Security.generate_password
module functions
module Security
    module_function
    def generate_password
        ('a'..'z').sample(8)
    end
end
Security.generate_password
respond_to?(:super)
module Sanitizer
    def save
        puts "sanitized"
        super
    end
end

module Persistance
    def save
        puts "saved"
        super
    end
end
class User
    include Persistance
    include Sanitizer
end
respond_to?(:super)
module Sanitizer
    def save
        puts "sanitized"
        super
    end
end
module Persistance
    def save
        puts "saved"
        super
    end
end
class User
    include Persistance
    include Sanitizer
end
respond_to?(:super)
 > User.new.save
=> sanitized
=> saved
=> save: super: no superclass method save (NoMeth
respond_to?(:super)
module Sanitizer
    def save
        puts "sanitized"
        super if respond_to?(:super)
    end
end

module Persistance
    def save
        puts "saved"
        super if respond_to?(:super)
    end
end
class User
    include Persistance
    include Sanitizer
end
respond_to?(:super)
module Sanitizer
    def save
        puts "sanitized"
        super if respond_to?(:super)
    end
end
module Persistance
    def save
        puts "saved"
        super if respond_to?(:super)
    end
end
class User
    include Persistance
    include Sanitizer
end
respond_to?(:super)
> User.new.save
=> sanitized
respond_to?(:super)
module Sanitizer
    def save
        puts "sanitized"
        super if defined?(super)
    end
end

module Persistance
    def save
        puts "saved"
        super if defined?(super)
    end
end
class User
    include Persistance
    include Sanitizer
end
respond_to?(:super)
 > User.new.save
=> sanitized
=> saved
Class.include
module Sanitizer
    def save
        puts "sanitized"
        super if defined(super)
    end
end
module Persistance
    def save
        puts "saved"
        super if defined(super)
    end
end
class User
    include Persistance
    include Sanitizer
end
Class.include
module Sanitizer
    def save
        puts "sanitized"
        super if defined(super)
    end
end
module Persistance
    def save
        puts "saved"
        super if defined(super)
    end
end
class User
    include Persistance, Sanitizer
end
Class.include
 > User.new.save
=> saved
=> sanitized
Class.include
class User
    include Persistance, Sanitizer
end
Class.include
class User
    include Sanitizer, Persistance
end
Class.include
 > User.new.save
=> sanitized
=> saved
Block comments
=begin
  Objects don't specify their attributes
  directly, but rather infer them from the table definition
  with which they're linked. Adding, removing, and changing
  attributes and their type is done directly in the database.
=end
Ruby1.9 - each_with_object
 > (1..5).inject({}) do |i, hsh|
        hsh[i] = i*2
        hsh
    end
=> {1=>2, 2=>4, 3=>6, 4=>8, 5=>10}

                   VS
> (1..5).each_with_object({}) do |i, hsh|
    hsh[i] = i*2
   end
=> {1=>2, 2=>4, 3=>6, 4=>8, 5=>10}
Ruby1.9 - public_send
class User
    protected
    def destroy
        puts "destroyed"
    end
end
User.new.public_send(:destroy)
NoMethodError: protected method destroy called
Ruby1.9 - ObjectSpace.count_objects
ObjectSpace.count_objects
{
    :TOTAL=>76928,
    :FREE=>549,
    :T_OBJECT=>1363,
    :T_CLASS=>1008,
    :T_MODULE=>38,
    :T_FLOAT=>7,
    :T_STRING=>50339,
    :T_REGEXP=>234,
    :T_ARRAY=>7259,
    :T_HASH=>558,
    :T_FILE=>16,
    :T_DATA=>1695,
}
Ruby1.9 define_finalizer
str = "ruby1.9"

ObjectSpace.define_finalizer(str) do |object_id|
    puts "string was destroyed id: #{object_id}"
end

str = nil
GC.start

=> string was destroyed id: -607935038
Ruby1.9 call proc
  prc = proc { puts "proc called" }
1) prc.call(1) # 1.8
2) prc[2] # 1.8
3) prc.(3) # new
4) prc.===(4) # new
Ruby1.9 call proc
sleep_time = proc do |time|
    case time.hour
    when 0..6 then true
    else false
    end
end
case Time.now
when sleep_time
  puts "go to bed. now!"
else
  puts "work harder"
end
Ruby1.9 call proc
sleep_time = proc do |time|
    case time.hour
    when 0..6 then true
    else false
    end
end

case Time.now
when sleep_time
  puts "go to bed. now!"
else
  puts "work harder"
end
sleep_time.===(Time.now)
Questions?

More Related Content

What's hot

What's hot (20)

PHP 5 Magic Methods
PHP 5 Magic MethodsPHP 5 Magic Methods
PHP 5 Magic Methods
 
PL/SQL Unit Testing Can Be Fun!
PL/SQL Unit Testing Can Be Fun!PL/SQL Unit Testing Can Be Fun!
PL/SQL Unit Testing Can Be Fun!
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Codeware
CodewareCodeware
Codeware
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Steady with ruby
Steady with rubySteady with ruby
Steady with ruby
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
 
Swift internals
Swift internalsSwift internals
Swift internals
 
Beyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCodeBeyond Breakpoints: Advanced Debugging with XCode
Beyond Breakpoints: Advanced Debugging with XCode
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScript
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
EventMachine for RubyFuZa 2012
EventMachine for RubyFuZa   2012EventMachine for RubyFuZa   2012
EventMachine for RubyFuZa 2012
 
Twig tips and tricks
Twig tips and tricksTwig tips and tricks
Twig tips and tricks
 
C++ 11 usage experience
C++ 11 usage experienceC++ 11 usage experience
C++ 11 usage experience
 

Viewers also liked (7)

Nodejs + Rails
Nodejs + RailsNodejs + Rails
Nodejs + Rails
 
ACID - Transakcje
ACID - TransakcjeACID - Transakcje
ACID - Transakcje
 
Having fun with legacy apps
Having fun with legacy appsHaving fun with legacy apps
Having fun with legacy apps
 
Schema plus
Schema plusSchema plus
Schema plus
 
DDD, Rails and persistence
DDD, Rails and persistenceDDD, Rails and persistence
DDD, Rails and persistence
 
Cap Theorem
Cap TheoremCap Theorem
Cap Theorem
 
Tradycyjne indeksy w sql server
Tradycyjne indeksy w sql serverTradycyjne indeksy w sql server
Tradycyjne indeksy w sql server
 

Similar to Ruby tricks2

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
Nando Vieira
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 

Similar to Ruby tricks2 (20)

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Module Magic
Module MagicModule Magic
Module Magic
 
Metaprogramming Rails
Metaprogramming RailsMetaprogramming Rails
Metaprogramming Rails
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Dsl
DslDsl
Dsl
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Ruby tricks2