#15 - Ruby 2.0.0-rc2

02/11/2013 | Primary Language: Ruby | Duration 00:12:50

Ruby 2.0 introduces some new features and changes that could impact Ruby developers daily. In this episode we’ll explore topics such as Module Prepend, Keyword Arguments, Enumerable#lazy, amongst others. With Ruby 2.0 around the corner Ruby developers should be aware of these new changes and how they’ll impact your code.

Tags: ruby, ruby-2-0, module, prepend, enumerable

Download Ruby 2.0.0-rc2
puts RUBY_VERSION

## %i

puts %w{ruby is great}.inspect
puts %i{ruby is great}.inspect
puts %I{#{1 + 1} is great}.inspect

#to_h

h = {name: "Mark"}
puts h.to_h.inspect
User = Struct.new(:name)
user = User.new("Mark")

puts user.to_h.inspect
def href(link, options = {})
  raise TypeError.new("#{options} is not a Hash") unless options.is_a?(Hash)
end

href("http://www.metacasts.tv", [])
def href(link, options = {})
  if options.respond_to?(:to_h)
  else
    raise TypeError.new("#{options} does not respond_to :to_h")
  end
end

href("http://www.metacasts.tv", [])

Enumerable#lazy

class SlowNumbers
  include Enumerable

  def each
    sleep 1
    yield 1
    sleep 1
    yield 2
    sleep 1
    yield 3
  end

end

SlowNumbers.new.map {|x| x * 10}.each {|x| p x}
SlowNumbers.new.lazy.map {|x| x * 10}.each {|x| p x}

Keyword Arguments

def link_to(body, url_options = {}, html_options = {})
  puts %{body: #{body.inspect}}
  puts %{url_options: #{url_options.inspect}}
  puts %{html_options: #{html_options.inspect}}
end

link_to("Home", {}, {class: "active"})
def link_to(body, url_options: {}, html_options: {})
  puts %{body: #{body.inspect}}
  puts %{url_options: #{url_options.inspect}}
  puts %{html_options: #{html_options.inspect}}
end

link_to("Home", html_options: {class: "active"})

Module Prepend

module Upcaser
  def to_s
    super.upcase
  end
end

class User
  include Upcaser

  def to_s
    self.class.name
  end
end

puts User.new.to_s #=> "User"
module Upcaser
  def to_s
    super.upcase
  end
end

class User
  prepend Upcaser

  def to_s
    self.class.name
  end
end

puts User.new.to_s #=> "USER"
comments powered by Disqus