Ruby 2.0

Gabor Ratky / @rgabo

Timeline

  • Ruby 1.8: 2003 August
  • Ruby 1.9: 2007 December
  • Ruby 2.0.0-p0: 2013 February 24
  • Ruby 2.0.0-p195: 2013 May 14
  • Ruby 2.0.0-p247: 2013 June 27
  • Ruby 2.0.0-p353: 2013 November 22
  • Ruby 2.1.0-p0: 2013 December 25

Install

rvm

						
rvm install ruby-2.0.0
						
					

rbenv

						
rbenv install 2.0.0-p353
						
					

Compatibility

Deep changes

Bitmap garbage collection

Backwards compatible with 1.9

require() speed improvements

Big changes

Keyword arguments

today

						
def foo(foo: 'bar', baz: 'qux', **rest)
  # TODO
end

foo(baz: 'qux', foo: 'frob')
						
					

future

						
def foo(optional: 'default', required:)
end
						
					

Prepend

						
module Foo
  def somehing; end
end

class MyClass
  prepend Foo
end

MyClass.ancestors # =>[Foo, MyClass, Object...]
						
					
No more alias_method_chain

Lazy enumerators

            
to_infinity = (0..Float::Infinity)

beyond =to_infinity.lazy.select do |n|
  num % 42 == 0
end

100.times do { |n| puts beyond.next }
            
          

Enumerator#size

            
(1..100).to_a.permutation(4).size # => 94109400

enum = Enumerator.new(3) do |yielder| ...; end

def square_times(num)
  return to_enum(:square_times) {num ** 2} unless block_given?
  (num ** 2).times do |i|
    yield i
  end
end
            
          

Refinements

          
module Palindrome
  refine String do
    def palindrome?
      self == self.reverse
    end
  end
end

using Palindrome # Monkey patch now active for context

"saippuakivikauppias".palindrome? # => true
          
        

Small changes

Symbol array literal

            
%i[foo bar baz] # => [:foo, :bar, :baz]

%I[#{1 + 1}x #{2 + 2}x]   #=> [:"2x", :"4x"]
            
          

Binary search

            
haystack = (1..99999999)

haystack.bsearch do |needle|
  needle == 12345
end

# => 12345
            
          

UTF8 by default

Ruby 1.9

            
#!/usr/bin/env ruby1.9
#encoding: utf-8

puts "★"
            
          

Ruby 2.0

            
#!/usr/bin/env ruby-2.0

puts "★"
            
          

File directory

            
# Ruby 1.8
require File.dirname(__FILE__) + "/lib"
File.read(File.dirname(__FILE__) + "/.config")

# Ruby 1.9
require_relative 'lib'
File.read(File.dirname(__FILE__) + '/.config')

# Ruby 2.0
require_relative 'lib'
File.read(__dir__ + '/.config')
            
          

to_h

            
Car = Struct.new(:make, :model, :year) do
  def build
    #...
  end
end
car = Car.new('Toyota', 'Prius', 2014)
car.to_h # => {:make=>"Toyota", :model=>"Prius", :year=>2014}
nil.to_h # => {}
            
          

Implemented for:

  • nil
  • Struct
  • OpenStruct
  • Enumerable/Array

ETC

  • Unused variables can start with _
  • caller_locations
  • const_get understands namespaces
  • Rubygems Gemfile support
  • RDoc markdown support

and many more...

Thanks!