SlideShare uma empresa Scribd logo
1 de 27
Baixar para ler offline
Ruby 2
some new things

 David A. Black
  Lead Developer
  Cyrus Innovation
  @david_a_black

 Ruby Blind meetup
   April 10, 2013
About me
• Rubyist since 2000 (Pickaxe baby)
• Lead Developer, Cyrus Innovation
• Developer, author, trainer, speaker, event
  organizer
• Author of The Well-Grounded Rubyist
• Co-founder of Ruby Central
• Chief author of scanf.rb (standard library)
Today's topics
• Lazy enumerators
• Module#prepend
• String#bytes and friends
• Keyword arguments
• Miscellaneous changes and new features
Lazy enumerators
What's wrong with this code?
# find the first 10 multiples of 3

(0..Float::INFINITY).select {|x| x % 3 == 0 }.first(10)
Lazy enumerators
# find the first 10 multiples of 3

(0..Float::INFINITY).select {|x| x % 3 == 0 }.first(10)



It runs forever!
Lazy enumerators

# find the first 10 multiples of 3

(0..Float::INFINITY).lazy.select {|x| x % 3 == 0 }.first(10)
Lazy enumerators

# find the first 10 multiples of 3

(0..Float::INFINITY).lazy.select {|x| x % 3 == 0 }.first(10)

=> [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
Lazy enumerators
r = 0..Float::INFINITY
s = 0..Float::INFINITY

r.zip(s).first(5)   # runs forever
Lazy enumerators
r = 0..Float::INFINITY
s = 0..Float::INFINITY

r.lazy.zip(s).first(5)

=> [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
Lazy enumerators
# From Ruby source documentation

fib = Enumerator.new do |y|
  a = b = 1
  loop do
    y << a
    a, b = b, a + b
  end
end

fib.zip(0..Float::INFINITY).first(5)   # runs forever
Lazy enumerators

fib = Enumerator.new do |y|
  a = b = 1
  loop do
    y << a
    a, b = b, a + b
  end
end.lazy

fib.zip(0..Float::INFINITY).first(5)

# => [[1, 0], [1, 1], [2, 2], [3, 3], [5, 4]]
Lazy enumerators
• can be created via #lazy on an Enumerable
 • [1,2,3].lazy
 • (0..Float::INFINITY).lazy
 • an_enumerator.lazy (see Fibonacci
   example)
Module#prepend
What will the output be?
    class Person
      def talk
        puts "Hello"
      end
    end

    module Yeller
      def talk
        super
        puts "I said... HELLLLLOOO!!!!"
      end
    end

    class Person
      include Yeller
    end

    david = Person.new
    david.talk
Module#prepend
class Person
  def talk
    puts "Hello"
  end
end

module Yeller
  def talk
    super
    puts "I said... HELLLLLOOO!!!!"
  end
end

class Person
  include Yeller
end

david = Person.new
david.talk

# => Hello
p Person.ancestors

# => [Person, Yeller, Object, Kernel, BasicObject]
Module#prepend
What will the output be?
    class Person
      def talk
        puts "Hello"
      end
    end

    module Yeller
      def talk
        super
        puts "I said... HELLLLLOOO!!!!"
      end
    end

    class Person
      prepend Yeller
    end

    david = Person.new
    david.talk
Module#prepend
class Person
  def talk
    puts "Hello"
  end
end

module Yeller
  def talk
    super
    puts "I said... HELLLLLOOO!!!!"
  end
end

class Person
  prepend Yeller
end

david = Person.new
david.talk

# => Hello
     I said... HELLLLLOOO!!!!
p Person.ancestors

# => [Yeller, Person, Object, Kernel, BasicObject]
Module#prepend
• Puts the module *before* the receiver
(class or module) in the method lookup
path
• A good way to avoid messing with alias
     class Person
       def talk
         puts "Hello!"
       end
     end

     class Person
       alias old_talk talk
       def talk
         old_talk
         puts "I said... HELLLLLOOO!!!!"
       end
     end
String#bytes/each_byte
         (and friends)
• String#bytes, #lines, #chars, #codepoints
  now return arrays
• #each_byte/line/char/codepoint still return
  enumerators
• Saves you having to do #to_a when you
  want an array
Keyword arguments
    def my_method(a, b, c: 3)
      p a, b, c
    end

    my_method(1, 2)            # 1 2 3
    my_method(1, 2, c: 4)      # 1 2 4




  Lets you specify a default value for a
  parameter, and use the parameter's name in
  your method call
Keyword arguments

def my_method(a, b, *array, c: 3)
  p a, b, array, c
end

my_method(1, 2, 3, 4, c: 5) # 1, 2, [3, 4], 5




      Non-keyword arguments still work
      essentially the same way that they did.
Keyword arguments

def my_method(a, b, *array, c: 3, **others)
  p a, b, array, c, others
end

my_method(1, 2, 3, 4, c: 5, d: 6, e: 7)
  # 1, 2, [3, 4], 5, {:d=>6, :e=>7}



     Extra keyword arguments get passed
     along in the **others parameter.
Keyword arguments

  def my_method(a, b, c)
    p a, b, c
  end

  my_method(1, 2, z: 3)    # 1 2 {:z=>3}



   Hash-like arguments that don't
   correspond to a named argument get
   passed along as a hash.
Keyword arguments
Order doesn't matter:
  class Person
    attr_accessor :name, :email, :age

    def initialize(name: "", email: "", age: 0)
      self.name = name
      self.email = email
      self.age = age
    end
  end

  david = Person.new(email: "dblack@rubypal.com",
                     name: "David",
                     age: Float::INFINITY)
Miscellaneous
•   %i{} and %I{}
•   Default encoding now UTF-8 (no need for magic
    comment)
•   Struct#to_h, nil#to_h, Hash#to_h
•   Kernel#Hash (like Array, Integer, Float)
•   const_get now parses nested constants
    •   Object.const_get("A::B::C")
•   #inspect doesn't call #to_s any more
• Questions?
• Comments?


 David A. Black
  Lead Developer
  Cyrus Innovation
  @david_a_black

  Ruby Blind meetup
    April 10, 2013

Mais conteúdo relacionado

Mais procurados

Hacker 101/102 - Introduction to Programming w/Processing
Hacker 101/102 - Introduction to Programming w/ProcessingHacker 101/102 - Introduction to Programming w/Processing
Hacker 101/102 - Introduction to Programming w/ProcessingDan Chudnov
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)RORLAB
 
How to write test in Django
How to write test in DjangoHow to write test in Django
How to write test in DjangoShunsuke Hida
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a PythonistRaji Engg
 
Nedap Rails Workshop
Nedap Rails WorkshopNedap Rails Workshop
Nedap Rails WorkshopAndre Foeken
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoNina Zakharenko
 
Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Scott Wlaschin
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Andre Foeken
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 

Mais procurados (20)

An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Elixir for rubysts
Elixir for rubystsElixir for rubysts
Elixir for rubysts
 
Hacker 101/102 - Introduction to Programming w/Processing
Hacker 101/102 - Introduction to Programming w/ProcessingHacker 101/102 - Introduction to Programming w/Processing
Hacker 101/102 - Introduction to Programming w/Processing
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
How to write test in Django
How to write test in DjangoHow to write test in Django
How to write test in Django
 
Kidscode00
Kidscode00Kidscode00
Kidscode00
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
 
Nedap Rails Workshop
Nedap Rails WorkshopNedap Rails Workshop
Nedap Rails Workshop
 
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina ZakharenkoElegant Solutions For Everyday Python Problems - Nina Zakharenko
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
 
Python Part 2
Python Part 2Python Part 2
Python Part 2
 
Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)Four Languages From Forty Years Ago (NewCrafts 2019)
Four Languages From Forty Years Ago (NewCrafts 2019)
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)
 
Dsl
DslDsl
Dsl
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Clean code
Clean codeClean code
Clean code
 

Semelhante a Ruby 2: some new things

Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in StyleBhavin Javia
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
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
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Brian Hogan
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1Pavel Tyk
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like PythonistaChiyoung Song
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Wen-Tien Chang
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101Nando Vieira
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the BasicsMichael Koby
 
python within 50 page .ppt
python within 50 page .pptpython within 50 page .ppt
python within 50 page .pptsushil155005
 

Semelhante a Ruby 2: some new things (20)

Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Ruby
RubyRuby
Ruby
 
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
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Rails by example
Rails by exampleRails by example
Rails by example
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Ruby 2.0
Ruby 2.0Ruby 2.0
Ruby 2.0
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Metaprogramming 101
Metaprogramming 101Metaprogramming 101
Metaprogramming 101
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
python within 50 page .ppt
python within 50 page .pptpython within 50 page .ppt
python within 50 page .ppt
 

Último

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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 textsMaria Levchenko
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Último (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Ruby 2: some new things

  • 1. Ruby 2 some new things David A. Black Lead Developer Cyrus Innovation @david_a_black Ruby Blind meetup April 10, 2013
  • 2. About me • Rubyist since 2000 (Pickaxe baby) • Lead Developer, Cyrus Innovation • Developer, author, trainer, speaker, event organizer • Author of The Well-Grounded Rubyist • Co-founder of Ruby Central • Chief author of scanf.rb (standard library)
  • 3. Today's topics • Lazy enumerators • Module#prepend • String#bytes and friends • Keyword arguments • Miscellaneous changes and new features
  • 4. Lazy enumerators What's wrong with this code? # find the first 10 multiples of 3 (0..Float::INFINITY).select {|x| x % 3 == 0 }.first(10)
  • 5. Lazy enumerators # find the first 10 multiples of 3 (0..Float::INFINITY).select {|x| x % 3 == 0 }.first(10) It runs forever!
  • 6. Lazy enumerators # find the first 10 multiples of 3 (0..Float::INFINITY).lazy.select {|x| x % 3 == 0 }.first(10)
  • 7. Lazy enumerators # find the first 10 multiples of 3 (0..Float::INFINITY).lazy.select {|x| x % 3 == 0 }.first(10) => [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
  • 8. Lazy enumerators r = 0..Float::INFINITY s = 0..Float::INFINITY r.zip(s).first(5) # runs forever
  • 9. Lazy enumerators r = 0..Float::INFINITY s = 0..Float::INFINITY r.lazy.zip(s).first(5) => [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
  • 10. Lazy enumerators # From Ruby source documentation fib = Enumerator.new do |y| a = b = 1 loop do y << a a, b = b, a + b end end fib.zip(0..Float::INFINITY).first(5) # runs forever
  • 11. Lazy enumerators fib = Enumerator.new do |y| a = b = 1 loop do y << a a, b = b, a + b end end.lazy fib.zip(0..Float::INFINITY).first(5) # => [[1, 0], [1, 1], [2, 2], [3, 3], [5, 4]]
  • 12. Lazy enumerators • can be created via #lazy on an Enumerable • [1,2,3].lazy • (0..Float::INFINITY).lazy • an_enumerator.lazy (see Fibonacci example)
  • 13. Module#prepend What will the output be? class Person def talk puts "Hello" end end module Yeller def talk super puts "I said... HELLLLLOOO!!!!" end end class Person include Yeller end david = Person.new david.talk
  • 14. Module#prepend class Person def talk puts "Hello" end end module Yeller def talk super puts "I said... HELLLLLOOO!!!!" end end class Person include Yeller end david = Person.new david.talk # => Hello
  • 15. p Person.ancestors # => [Person, Yeller, Object, Kernel, BasicObject]
  • 16. Module#prepend What will the output be? class Person def talk puts "Hello" end end module Yeller def talk super puts "I said... HELLLLLOOO!!!!" end end class Person prepend Yeller end david = Person.new david.talk
  • 17. Module#prepend class Person def talk puts "Hello" end end module Yeller def talk super puts "I said... HELLLLLOOO!!!!" end end class Person prepend Yeller end david = Person.new david.talk # => Hello I said... HELLLLLOOO!!!!
  • 18. p Person.ancestors # => [Yeller, Person, Object, Kernel, BasicObject]
  • 19. Module#prepend • Puts the module *before* the receiver (class or module) in the method lookup path • A good way to avoid messing with alias class Person def talk puts "Hello!" end end class Person alias old_talk talk def talk old_talk puts "I said... HELLLLLOOO!!!!" end end
  • 20. String#bytes/each_byte (and friends) • String#bytes, #lines, #chars, #codepoints now return arrays • #each_byte/line/char/codepoint still return enumerators • Saves you having to do #to_a when you want an array
  • 21. Keyword arguments def my_method(a, b, c: 3) p a, b, c end my_method(1, 2) # 1 2 3 my_method(1, 2, c: 4) # 1 2 4 Lets you specify a default value for a parameter, and use the parameter's name in your method call
  • 22. Keyword arguments def my_method(a, b, *array, c: 3) p a, b, array, c end my_method(1, 2, 3, 4, c: 5) # 1, 2, [3, 4], 5 Non-keyword arguments still work essentially the same way that they did.
  • 23. Keyword arguments def my_method(a, b, *array, c: 3, **others) p a, b, array, c, others end my_method(1, 2, 3, 4, c: 5, d: 6, e: 7) # 1, 2, [3, 4], 5, {:d=>6, :e=>7} Extra keyword arguments get passed along in the **others parameter.
  • 24. Keyword arguments def my_method(a, b, c) p a, b, c end my_method(1, 2, z: 3) # 1 2 {:z=>3} Hash-like arguments that don't correspond to a named argument get passed along as a hash.
  • 25. Keyword arguments Order doesn't matter: class Person attr_accessor :name, :email, :age def initialize(name: "", email: "", age: 0) self.name = name self.email = email self.age = age end end david = Person.new(email: "dblack@rubypal.com", name: "David", age: Float::INFINITY)
  • 26. Miscellaneous • %i{} and %I{} • Default encoding now UTF-8 (no need for magic comment) • Struct#to_h, nil#to_h, Hash#to_h • Kernel#Hash (like Array, Integer, Float) • const_get now parses nested constants • Object.const_get("A::B::C") • #inspect doesn't call #to_s any more
  • 27. • Questions? • Comments? David A. Black Lead Developer Cyrus Innovation @david_a_black Ruby Blind meetup April 10, 2013