An example of form inheritance and "The Ruby way"

In my search for a transition from a decade of C ++ to Ruby, I find myself a second guess on how to accomplish the simplest things. Given the classic form example below, I wonder if this is the “Ruby Way”. Although I believe that nothing happens incorrectly in the code below, I have the feeling that I am not using the full power of Ruby.

class Shape
  def initialize
  end
end

class TwoD < Shape
  def initialize
    super()
  end

  def area
     return 0.0
  end
end

class Square < TwoD
  def initialize( side )
    super()
    @side = side
  end

  def area
    return @side * @side
  end
end

def shapeArea( twod )
  puts twod.area
end

square = Square.new( 2 )

shapeArea( square ) # => 4

Is it implemented "Ruby Way"? If not, how would you do it?

+3
source share
2 answers

The great thing about Ruby is that you don't need to use inheritance just to provide a contract for implemented methods. Instead, you could do this:

class Square
  def initialize(side)
    @side = side
  end

  def area
    @side * @side
  end
end

class Circle
  def initialize(radius)
    @radius = radius
  end

  def area
    @radius * @radius * 3.14159
  end
end

shapeArea(Square.new(2))
shapeArea(Circle.new(5))

, . twod ( Ruby , twod ), .

+7

- " ", ++ ( ) ruby ​​( ), :

class TwoD < Shape
  ...
  def area
    # make this truly look pure-virtual
    raise NoMethodError, "Pure virtual function called"
  end
end

, , :

class Module
  def pure_virtual(*syms)
    syms.each do |s|
      define_method(s) { raise NoMethodError, "Pure virtual function called: #{s}" }
    end
  end
end

class TwoD < Shape
  pure_virtual :area
  ...
end
+2

Source: https://habr.com/ru/post/1711779/


All Articles