Ruby/Class/include

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Add extension from a module for an object not class

class Person
  attr_reader :name, :age, :occupation
  def initialize(name, age, occupation)
    @name, @age, @occupation = name, age, occupation
  end
  def isIn?
    true
  end
end
jimmy = Person.new("J", 21, "reporter")
clark = Person.new("C", 35, "reporter")
jimmy.isIn?                                     # => true
clark.isIn?                                     # => true
 
module SuperPowers
  def fly
    "Flying!"
  end
  def leap(what)
    "Leaping #{what} in a single bound!"
  end
  def mild_mannered?
    false
  end
  def superhero_name
    "Superman"
  end
end
clark.extend(SuperPowers)
clark.superhero_name                          # => "Superman"
clark.fly                                     # => "Flying!"
clark.isIn?                                   # => false
jimmy.isIn?                                   # => true



Extending Specific Objects with Modules

class Person
  attr_reader :name, :age, :occupation
  def initialize(name, age, occupation)
    @name, @age, @occupation = name, age, occupation
  end
  def mild_mannered?
    true
  end
end
module SuperPowers
  def fly
    "Flying!"
  end
  def leap(what)
    "Leaping #{what} in a single bound!"
  end
  def mild_mannered?
    false
  end
  def superhero_name
    "Superman"
  end
end
class Person
  extend SuperPowers
end
# which is equivalent to:
Person.extend(SuperPowers)
Person.superhero_name                   # => "Superman"
Person.fly                              # => "Flying!"



Include a module into a class

#!/usr/bin/env ruby
module Dice
  # virtual roll of a pair of dice
  def roll
    r_1 = rand(6); r_2 = rand(6)
    r1 = r_1>0?r_1:1; r2 = r_2>0?r_2:6
    total = r1+r2
    printf( "You rolled %d and %d (%d).\n", r1, r2, total )
    total
  end
end
class Game
 include Dice
end
g = Game.new
g.roll



Include module with same method name

module MyModule
  def potato
    "A"
  end
end
module ModuleB
  def potato
    "B"
  end
end
class Potato
  include MyModule
  include ModuleB
end
puts Potato.new.potato