SlideShare a Scribd company logo
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

PPT
Rapid Application Development using Ruby on Rails
PPTX
Children of Ruby
KEY
Learn Ruby 2011 - Session 1
KEY
Learn Ruby 2011 - Session 2
KEY
Learn Ruby 2011 - Session 3
KEY
Dojo for programmers (TXJS 2010)
KEY
UT on Rails3 2010- Week 2
PDF
JavaScript-Core
Rapid Application Development using Ruby on Rails
Children of Ruby
Learn Ruby 2011 - Session 1
Learn Ruby 2011 - Session 2
Learn Ruby 2011 - Session 3
Dojo for programmers (TXJS 2010)
UT on Rails3 2010- Week 2
JavaScript-Core

What's hot (20)

PPTX
Moo the universe and everything
PDF
Ruby para-programadores-php
PDF
[Start] Scala
KEY
Scala Introduction
KEY
Learn Ruby 2011 - Session 4 - Objects, Oh My!
PDF
Metaprogramming ruby
PDF
Rails 3 Beginner to Builder 2011 Week 2
PDF
RoR_2_Ruby
PDF
Swift Basics
PDF
Metaprogramming in Ruby
PDF
An Introduction to Scala for Java Developers
PDF
A Deep Dive into Javascript
PPT
java introduction
PPTX
An Introduction to Scala
PPTX
Ruby for .NET developers
PDF
Intro to Objective C
PPTX
Ruby for PHP developers
PDF
Introduction to Scala : Clueda
PDF
Ruby on Rails : 簡介與入門
KEY
Fwt ios 5
Moo the universe and everything
Ruby para-programadores-php
[Start] Scala
Scala Introduction
Learn Ruby 2011 - Session 4 - Objects, Oh My!
Metaprogramming ruby
Rails 3 Beginner to Builder 2011 Week 2
RoR_2_Ruby
Swift Basics
Metaprogramming in Ruby
An Introduction to Scala for Java Developers
A Deep Dive into Javascript
java introduction
An Introduction to Scala
Ruby for .NET developers
Intro to Objective C
Ruby for PHP developers
Introduction to Scala : Clueda
Ruby on Rails : 簡介與入門
Fwt ios 5
Ad

Similar to Ruby :: Training 1 (20)

PDF
Ruby — An introduction
PPTX
Code for Startup MVP (Ruby on Rails) Session 2
PPTX
From Ruby to Scala
PPTX
Ruby basics
ZIP
Meta Programming in Ruby - Code Camp 2010
PDF
Ruby 2: some new things
KEY
Metaprogramming Primer (Part 1)
PDF
The Dark Art of Rails Plugins (2008)
PPTX
Why Ruby?
KEY
Ruby on Rails Training - Module 1
PPT
Ruby for C# Developers
KEY
Learn Ruby 2011 - Session 5 - Looking for a Rescue
PPTX
Ruby object model - Understanding of object play role for ruby
PDF
Introducing BoxLang : A new JVM language for productivity and modularity!
PPT
Rubyforjavaprogrammers 1210167973516759-9
PPT
Rubyforjavaprogrammers 1210167973516759-9
KEY
Ruby: Beyond the Basics
PPTX
Python 2. classes- cruciql for students objects1.pptx
KEY
Introduction to Ruby
PDF
fuser interface-development-using-jquery
Ruby — An introduction
Code for Startup MVP (Ruby on Rails) Session 2
From Ruby to Scala
Ruby basics
Meta Programming in Ruby - Code Camp 2010
Ruby 2: some new things
Metaprogramming Primer (Part 1)
The Dark Art of Rails Plugins (2008)
Why Ruby?
Ruby on Rails Training - Module 1
Ruby for C# Developers
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Ruby object model - Understanding of object play role for ruby
Introducing BoxLang : A new JVM language for productivity and modularity!
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
Ruby: Beyond the Basics
Python 2. classes- cruciql for students objects1.pptx
Introduction to Ruby
fuser interface-development-using-jquery
Ad

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

  • #8: Range - Интервал
  • #23: Template functions = Функции шаблоны