Ruby/Class/Class Methods

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

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

Содержание

Class methods give you the mechanism to properly implement the object counter

class Square
  def initialize
    if defined?(@@number_of_squares)
      @@number_of_squares += 1
    else
      @@number_of_squares = 1
    end
  end
  def Square.count
    @@number_of_squares
  end
end
a = Square.new
puts Square.count
b = Square.new
puts Square.count
c = Square.new
puts Square.count



Creating Class Methods

# Besides class variables, you can create class methods in Ruby. 
# You can call a class method using just the name of the class. 
class Mathematics
  def Mathematics.add(operand_one, operand_two)
    return operand_one + operand_two
  end
end
 
puts "1 + 2 = " + Mathematics.add(1, 2).to_s



Static class method

#!/usr/bin/env ruby
class Area
  def Area.rect( length, width, units="inches" )
    area = length*width
    printf( "The area of this rectangle is %.2f %s.", area, units )
    sprintf( "%.2f", area )
  end
end
Area.rect( 12.5, 16 )



The area method is made available in all objects of class Square,

# so it"s considered to be an object method.
class Square
  def initialize(side_length)
    @side_length = side_length
  end
  def area
    @side_length * @side_length
  end
end