SlideShare a Scribd company logo
1 of 25
TRAINING 1
RUBY
Pavel Tsiukhtsiayeu
github.com/paveltyk
Ruby :: introduction
• Ruby is a object oriented language
• Truly OBJECT ORIENTED language !!!
• Designed and developed by Yukihiro “Matz” Matsumoto
Ruby :: introduction
                • Yukihiro “Matz” Matsumoto
                  • まつもとゆきひろ 松本行弘
                • Born 14 Apr 1965
                • As of 2012, Matsumoto is the
                  Chief Architect of Ruby at Heroku
                • https://github.com/matz
                • https://twitter.com/yukihiro_matz
Ruby :: introduction
• Ruby is a object oriented language
• Truly OBJECT ORIENTED language !!!
• Designed and developed by Yukihiro “Matz” Matsumoto
• Ruby written for humans, not machines
  • Often … computer engineers … focus on the machines. But in fact
    we need to focus on humans… We are the masters. They are the
    slaves.
• Rich yet Flexible Syntax
  • 3.downto(0) { |i| puts "Countdown: #{i}..."}
  • user = User.find_by_name(„Matz‟) and user.say_hi
• Ruby makes developers HAPPY
Ruby :: variables and constants
• Sigils denote scopes
• Sigil - symbol attached to variable name
• $ - global ($global_variable)
• @ - instance variable (@instance_variable)
• @@ - class variable (@@class_variable)
• [A-Z] - constants
   • CONSTANT - all upper case
   • MyClass - titleized
• [_a-z] - local variables (local_variable)
• You never see variable declarations
• But you always know what you are dealing with
• Clean and Readable code
Ruby :: methods, naming convention
• object.find_by_name - preferable snake case
• object.dangerous! - Bang!!! method
• object.boolean_predicate? - returns true or false
 def Name # do not do this
  “I‟m a method”
 end

 Name = “I‟m a constant”
 Name
 #=> “I‟m a constant”
 Name()
 #=> “I‟m a method”
Ruby :: truly object oriented
• Everything is an object. Everything!
• 1.class => Fixnum
• “hello”.class => String
• [1, „hello‟, nil].class => Array
• nil.class => NilClass
• true.class => TrueClass
• false.class => FalseClass
• (1..10).class => Range
• /hello/.class => Regexp
• Fixnum.class => Class
• Class.class => Class %)) WHAT!!
Ruby :: nil is an object
• nil.to_s => “”
• nil.to_i => 0
• nil.nil? => true
• nil.blank? => true (Rails extension)
• In statements (if, case, etc.) only nil and false evaluated
 as FALSE
Ruby :: syntax
• Almost everything can be written in different ways
  • Easy things stay clean and easy
  • Difficult things maintain readability
• Parentheses are optional
  • find_by_name 'Matz'
  • find_by_name('Matz')
• Blocks
  • { |a| #do something with a }
  • do |a|
     • #do something with a
  • end
• 1..5 eq Range.new(1,5) and /^Hi/ eq Regexp.new(“^Hi”)
Ruby :: syntax sugar
• Did you ever do?
  • puts “Hello, World!”
• puts - is it a language construct?
  • It‟s a method defined in Kernel :)
• public, private, protected - language constructs?
  • No! They are class methods!
• +, -, *, ==, etc. are methods too :)
   • 1 + 2 equivalent to 1.+(2) equivalent to 1.send :+, 2
• =, .., ..., !, not, &&, and, ||, or, !=, !~ What about these?
• These are REAL operators
Ruby :: classes
• Ready to know the truth?
 class MyClass                     MyClass = Class.new do
  def name                          def name
    “MyClass”                        “MyClass”
  end                               end
 end                               end



• Classes are instances of a class Class
• Class.ancestors =>
  • [Class, Module, Object, Kernel, BasicObject]
Ruby :: open classes
• Classes in Ruby are always open
• Change them any time (avoid monkey patching core
 classes)
 nil.dance #=> NoMethodError
 class NilClass
  def dance
    “Spin”
  end
 end
 nil.dance #=> “Spin”


 • Rails adds many handy methods to core Ruby classes:
 • blank?, present?, presence, etc.
Ruby :: inheritance
• Ruby has NO multiple inheritance
• Ruby has single inheritance + MIXINS
• By default all classes inherit from Object
• Object inherit from BasicObject (ruby 1.9)
• Object.instance_methods.size => 112
• BasicObject.instance_methods.size => 7
Ruby :: inheritance, message dispatching
 • kate.dance
                                      BasicObject
 • kate.send :dance



                                        Object



      my_object.method_missing
         my_object.send :dance         MyClass



• What happens if method not found?
• Exception raised: NoMethodError
Ruby :: self & method missing
• self = current object
• Every method has 3 parts: object.do_the_thing(10)
  • object - receiver
  • do_the_thing - message
  • 10 - arguments
  • receiver is self, if not explicit receiver given
• What method_missing can be useful for
  • Person.find_by_name(„Matz‟)
  • Write DSL (XML generators)
  • Proxy pattern
  • Method delgation
Ruby :: modules
• A namespace for constants (such as classes)
• A place to define methods (can be later used by a class or
  an object)
• Unlike a class, can‟t have instances & instance variables
• Class (as a class name) inherit from class Module
  • Class (as a class name) has more functionality (#new for example)
• A key element of MIXIN

 module Dance                      Dance = Module.new do
  def do_the_trick                  def do_the_trick
   “Back flip”                       “Back flip”
  end                               end
 end                               end
Ruby :: MIXINS
• Mixins are used widely in Ruby
• Please behave like Enumerable: include Enumerable
class Band                                                find | detect
 include Enumerable                                       find_all | select
                                                          map | collect
 attr_accessor :members                                   inject, reject
                                                          all? any? one? none?
 def each(&block)                                         min max
  members.each{ |member| block.call(member) }
 end                                                      AND MORE
end

metallica = Band.new
metallica.members = [„James‟, „Lars‟, „Kirk‟, „Robert‟]
metallica.find_all { |m| m.size > 4 }
#=> [„James‟, „Robert‟]
Ruby :: MIXINS
• What happens when you include a module?
• class Band;end
• Band.ancestors => [Band, Object, Kernel, BasicObject]
  • class Band
  • include Enumerable
  • end
• Band.ancestors =>
  • [Band, Enumerable, Object, Kernel, BasicObject]
• Ruby creates an anonymous proxy class (“include” class)
  containing the module‟s methods: Enumerable
• Ruby inserts this proxy class in the inheritance chain right
  above current class: Band < Enumerable < Object …
Ruby :: MIXIN
• Try to solve this
module A                           Object
 def name; “I‟m A”; end
end
module B                           Object
                                     A
 def name; “I‟m B”; end
end
class MyClass
                                   Object
                                     B
                                     A
 include A
 Include B
end
                                   MyClass
MyClass.new.name      => “I‟m B”
Ruby :: MIXINS & eigenclasses
• You can extend individual object with module‟s methods
module Dancer
 def dance
  “Swing”
 end
end
class Cat
end
jane = Cat.new
jane.extend(Dancer)
jane.dance #=> “Swing”
bob = Cat.new
bob.dance #=> ???
               NoMethodError

• Ruby created eigenclass, and added proxy class
  • (jane eigenclass) < (Dancer) < Cat
Ruby :: MIXINS & eigenclasses
• You can define methods on individual objects
class Cat
end
jane = Cat.new
def jane.dance
  “Crawl”
end
jane.dance #=> “Crawl”
bob = Cat.new
bob.dance #=> NoMethodError


• jane‟s eigenclass now has #dance method
Ruby :: Blocks
• Blocks are heavily used in Ruby
• Callbacks
  • after_create lambda { |u| u.send_message }
  • before_validate lambda { |u| u.clear_name }
• Template functions
   • [1,2,3].map { |a| a * 2 } #=> [2,4,6]
   • [1,2,3].all? { |a| a > 2 } #=> false
• Wrapping logic
  • File.open(„hello.txt‟, „w‟) { |f| f.puts „Hello‟ }
• Lazy evaluation
   • Rails.cache.fetch(:jobs) { heavy_task }
Ruby :: alternative syntax
• Array
  • [„cat‟, „dog‟]
  • %w(cat dog) - parentheses may vary: %w{..} %w[..] %w!..!
  • %W(cat #{var} dog)
• Regexp
  • /^cat/
  • %r(^cat) - parentheses may vary
• String
  • „Hello, World‟ and “Hello, Word!”
  • %q(Hello, World!) - single quoted string
  • %Q(Hello, World!) - double quoted string (interpolation occurs)
  • %(Hello, World!)
  • <<HERE_DOC
  • Hello, World!
  • HERE_DOC
Ruby :: Q&A
• Q&A?
Ruby :: what do I do next?
• http://tryruby.org
• http://koans.heroku.com

More Related Content

What's hot

Moo the universe and everything
Moo the universe and everythingMoo the universe and everything
Moo the universe and everythingHenry Van Styn
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-phpJuan Maiz
 
Learn Ruby 2011 - Session 4 - Objects, Oh My!
Learn Ruby 2011 - Session 4 - Objects, Oh My!Learn Ruby 2011 - Session 4 - Objects, Oh My!
Learn Ruby 2011 - Session 4 - Objects, Oh My!James Thompson
 
Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 2Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 2Richard Schneeman
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
A Deep Dive into Javascript
A Deep Dive into JavascriptA Deep Dive into Javascript
A Deep Dive into JavascriptTiang Cheng
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to ScalaBrent Lemons
 
Ruby for .NET developers
Ruby for .NET developersRuby for .NET developers
Ruby for .NET developersMax Titov
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective CAshiq Uz Zoha
 
Ruby for PHP developers
Ruby for PHP developersRuby for PHP developers
Ruby for PHP developersMax Titov
 
Introduction to Scala : Clueda
Introduction to Scala : CluedaIntroduction to Scala : Clueda
Introduction to Scala : CluedaAndreas Neumann
 
Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Wen-Tien Chang
 

What's hot (20)

Moo the universe and everything
Moo the universe and everythingMoo the universe and everything
Moo the universe and everything
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 
[Start] Scala
[Start] Scala[Start] Scala
[Start] Scala
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Learn Ruby 2011 - Session 4 - Objects, Oh My!
Learn Ruby 2011 - Session 4 - Objects, Oh My!Learn Ruby 2011 - Session 4 - Objects, Oh My!
Learn Ruby 2011 - Session 4 - Objects, Oh My!
 
Metaprogramming ruby
Metaprogramming rubyMetaprogramming ruby
Metaprogramming ruby
 
Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 2Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 2
 
RoR_2_Ruby
RoR_2_RubyRoR_2_Ruby
RoR_2_Ruby
 
Swift Basics
Swift BasicsSwift Basics
Swift Basics
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
A Deep Dive into Javascript
A Deep Dive into JavascriptA Deep Dive into Javascript
A Deep Dive into Javascript
 
java introduction
java introductionjava introduction
java introduction
 
An Introduction to Scala
An Introduction to ScalaAn Introduction to Scala
An Introduction to Scala
 
Ruby for .NET developers
Ruby for .NET developersRuby for .NET developers
Ruby for .NET developers
 
Intro to Objective C
Intro to Objective CIntro to Objective C
Intro to Objective C
 
Ruby for PHP developers
Ruby for PHP developersRuby for PHP developers
Ruby for PHP developers
 
Introduction to Scala : Clueda
Introduction to Scala : CluedaIntroduction to Scala : Clueda
Introduction to Scala : Clueda
 
Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門Ruby on Rails : 簡介與入門
Ruby on Rails : 簡介與入門
 
Fwt ios 5
Fwt ios 5Fwt ios 5
Fwt ios 5
 

Similar to Ruby :: Training 1

Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scalatod esking
 
Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010ssoroka
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new thingsDavid Black
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Christopher Haupt
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)lazyatom
 
Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Mark Menard
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueJames Thompson
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyTushar Pal
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the BasicsMichael Koby
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to RubyMark Menard
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jqueryKostas Mavridis
 

Similar to Ruby :: Training 1 (20)

Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010Meta Programming in Ruby - Code Camp 2010
Meta Programming in Ruby - Code Camp 2010
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 
The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)The Dark Art of Rails Plugins (2008)
The Dark Art of Rails Plugins (2008)
 
Why Ruby?
Why Ruby? Why Ruby?
Why Ruby?
 
Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a Rescue
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for ruby
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
 
Introducing Ruby
Introducing RubyIntroducing Ruby
Introducing Ruby
 
04 inheritance
04 inheritance04 inheritance
04 inheritance
 

Ruby :: Training 1

  • 2. Ruby :: introduction • Ruby is a object oriented language • Truly OBJECT ORIENTED language !!! • Designed and developed by Yukihiro “Matz” Matsumoto
  • 3. Ruby :: introduction • Yukihiro “Matz” Matsumoto • まつもとゆきひろ 松本行弘 • Born 14 Apr 1965 • As of 2012, Matsumoto is the Chief Architect of Ruby at Heroku • https://github.com/matz • https://twitter.com/yukihiro_matz
  • 4. Ruby :: introduction • Ruby is a object oriented language • Truly OBJECT ORIENTED language !!! • Designed and developed by Yukihiro “Matz” Matsumoto • Ruby written for humans, not machines • Often … computer engineers … focus on the machines. But in fact we need to focus on humans… We are the masters. They are the slaves. • Rich yet Flexible Syntax • 3.downto(0) { |i| puts "Countdown: #{i}..."} • user = User.find_by_name(„Matz‟) and user.say_hi • Ruby makes developers HAPPY
  • 5. Ruby :: variables and constants • Sigils denote scopes • Sigil - symbol attached to variable name • $ - global ($global_variable) • @ - instance variable (@instance_variable) • @@ - class variable (@@class_variable) • [A-Z] - constants • CONSTANT - all upper case • MyClass - titleized • [_a-z] - local variables (local_variable) • You never see variable declarations • But you always know what you are dealing with • Clean and Readable code
  • 6. Ruby :: methods, naming convention • object.find_by_name - preferable snake case • object.dangerous! - Bang!!! method • object.boolean_predicate? - returns true or false def Name # do not do this “I‟m a method” end Name = “I‟m a constant” Name #=> “I‟m a constant” Name() #=> “I‟m a method”
  • 7. Ruby :: truly object oriented • Everything is an object. Everything! • 1.class => Fixnum • “hello”.class => String • [1, „hello‟, nil].class => Array • nil.class => NilClass • true.class => TrueClass • false.class => FalseClass • (1..10).class => Range • /hello/.class => Regexp • Fixnum.class => Class • Class.class => Class %)) WHAT!!
  • 8. Ruby :: nil is an object • nil.to_s => “” • nil.to_i => 0 • nil.nil? => true • nil.blank? => true (Rails extension) • In statements (if, case, etc.) only nil and false evaluated as FALSE
  • 9. Ruby :: syntax • Almost everything can be written in different ways • Easy things stay clean and easy • Difficult things maintain readability • Parentheses are optional • find_by_name 'Matz' • find_by_name('Matz') • Blocks • { |a| #do something with a } • do |a| • #do something with a • end • 1..5 eq Range.new(1,5) and /^Hi/ eq Regexp.new(“^Hi”)
  • 10. Ruby :: syntax sugar • Did you ever do? • puts “Hello, World!” • puts - is it a language construct? • It‟s a method defined in Kernel :) • public, private, protected - language constructs? • No! They are class methods! • +, -, *, ==, etc. are methods too :) • 1 + 2 equivalent to 1.+(2) equivalent to 1.send :+, 2 • =, .., ..., !, not, &&, and, ||, or, !=, !~ What about these? • These are REAL operators
  • 11. Ruby :: classes • Ready to know the truth? class MyClass MyClass = Class.new do def name def name “MyClass” “MyClass” end end end end • Classes are instances of a class Class • Class.ancestors => • [Class, Module, Object, Kernel, BasicObject]
  • 12. Ruby :: open classes • Classes in Ruby are always open • Change them any time (avoid monkey patching core classes) nil.dance #=> NoMethodError class NilClass def dance “Spin” end end nil.dance #=> “Spin” • Rails adds many handy methods to core Ruby classes: • blank?, present?, presence, etc.
  • 13. Ruby :: inheritance • Ruby has NO multiple inheritance • Ruby has single inheritance + MIXINS • By default all classes inherit from Object • Object inherit from BasicObject (ruby 1.9) • Object.instance_methods.size => 112 • BasicObject.instance_methods.size => 7
  • 14. Ruby :: inheritance, message dispatching • kate.dance BasicObject • kate.send :dance Object my_object.method_missing my_object.send :dance MyClass • What happens if method not found? • Exception raised: NoMethodError
  • 15. Ruby :: self & method missing • self = current object • Every method has 3 parts: object.do_the_thing(10) • object - receiver • do_the_thing - message • 10 - arguments • receiver is self, if not explicit receiver given • What method_missing can be useful for • Person.find_by_name(„Matz‟) • Write DSL (XML generators) • Proxy pattern • Method delgation
  • 16. Ruby :: modules • A namespace for constants (such as classes) • A place to define methods (can be later used by a class or an object) • Unlike a class, can‟t have instances & instance variables • Class (as a class name) inherit from class Module • Class (as a class name) has more functionality (#new for example) • A key element of MIXIN module Dance Dance = Module.new do def do_the_trick def do_the_trick “Back flip” “Back flip” end end end end
  • 17. Ruby :: MIXINS • Mixins are used widely in Ruby • Please behave like Enumerable: include Enumerable class Band find | detect include Enumerable find_all | select map | collect attr_accessor :members inject, reject all? any? one? none? def each(&block) min max members.each{ |member| block.call(member) } end AND MORE end metallica = Band.new metallica.members = [„James‟, „Lars‟, „Kirk‟, „Robert‟] metallica.find_all { |m| m.size > 4 } #=> [„James‟, „Robert‟]
  • 18. Ruby :: MIXINS • What happens when you include a module? • class Band;end • Band.ancestors => [Band, Object, Kernel, BasicObject] • class Band • include Enumerable • end • Band.ancestors => • [Band, Enumerable, Object, Kernel, BasicObject] • Ruby creates an anonymous proxy class (“include” class) containing the module‟s methods: Enumerable • Ruby inserts this proxy class in the inheritance chain right above current class: Band < Enumerable < Object …
  • 19. Ruby :: MIXIN • Try to solve this module A Object def name; “I‟m A”; end end module B Object A def name; “I‟m B”; end end class MyClass Object B A include A Include B end MyClass MyClass.new.name => “I‟m B”
  • 20. Ruby :: MIXINS & eigenclasses • You can extend individual object with module‟s methods module Dancer def dance “Swing” end end class Cat end jane = Cat.new jane.extend(Dancer) jane.dance #=> “Swing” bob = Cat.new bob.dance #=> ??? NoMethodError • Ruby created eigenclass, and added proxy class • (jane eigenclass) < (Dancer) < Cat
  • 21. Ruby :: MIXINS & eigenclasses • You can define methods on individual objects class Cat end jane = Cat.new def jane.dance “Crawl” end jane.dance #=> “Crawl” bob = Cat.new bob.dance #=> NoMethodError • jane‟s eigenclass now has #dance method
  • 22. Ruby :: Blocks • Blocks are heavily used in Ruby • Callbacks • after_create lambda { |u| u.send_message } • before_validate lambda { |u| u.clear_name } • Template functions • [1,2,3].map { |a| a * 2 } #=> [2,4,6] • [1,2,3].all? { |a| a > 2 } #=> false • Wrapping logic • File.open(„hello.txt‟, „w‟) { |f| f.puts „Hello‟ } • Lazy evaluation • Rails.cache.fetch(:jobs) { heavy_task }
  • 23. Ruby :: alternative syntax • Array • [„cat‟, „dog‟] • %w(cat dog) - parentheses may vary: %w{..} %w[..] %w!..! • %W(cat #{var} dog) • Regexp • /^cat/ • %r(^cat) - parentheses may vary • String • „Hello, World‟ and “Hello, Word!” • %q(Hello, World!) - single quoted string • %Q(Hello, World!) - double quoted string (interpolation occurs) • %(Hello, World!) • <<HERE_DOC • Hello, World! • HERE_DOC
  • 25. Ruby :: what do I do next? • http://tryruby.org • http://koans.heroku.com

Editor's Notes

  1. Range - Интервал
  2. Template functions = Функции шаблоны