| isPrime Method
1 class Integer
2 def isEven?()
3 if self % 2 == 0
4 then
5 true
6 else
7 false
8 end
9 end
|
| |
| |
| Ball Object using the Class command
1 class Ball
2 def initialize (color, radius, texture)
3 @color = color
4 @radius = radius
5 @texture = texture
6 end
7
8 def display
9 puts "Color ==> " + @color
10 puts "Radius ==> " + @radius.to_s
11 puts "Texture ==> " + @texture
12 end
13 end
|
| |
| |
| Creating an instance using the Ball object
1 require 'Ball'
2 newBall = Ball.new(‘green’, 1, ‘bouncy’)
3 newBall.display
|
| |
| |
| Using Inheritance-Rectangle class child to the Shape Class
1 class Rectangle < Shape
2 def initialize (length, width, color, label)
3 super
4 @area = length * width
5 end
6
7 def display
8 super.display
9 puts("Area ==> " + @area.to_s)
10 end
11 attr_accessor :area
12 end
|
| |
| |
| Using Overriding Methods with Inheritance
1 class Savings < Account
2 def calcInterest(months, apr)
3 monthlyYield = apr/12
4 ppm = months * monthlyYield
5 accountBalance * ppm
6 end
7 end
|
| |
| |
| Using Super Keyword with Inheritance
1 class Savings < Account
2 def calcInterest(months, apr)
3 oldInt = super #assuming an amount of interest
4 monthlyYield = apr/12
5 ppm = months * monthlyYield
6 (accountBalance * ppm) + oldInt
7 end
8 end
|
| |
| |
| Using Class Variables with Shape example
1 class Shape
2
3 @@numShapes = 0
4
5 def initialize (length, width, color, label)
6 @length = length
7 @width = width
8 @color = color
9 @label = label
10 @@numShapes = @@numShapes + 1
11 end
12
13 def display
14 puts "Shape ==> " + @label
15 puts "Length ==> " + @length.to_s
16 puts "Width ==> " + @width.to_s
17 puts "Color ==> " + @color
18 puts "Number of Shapes ==> " + @@numShapes.to_s
19 end
20 end
|
| |
| |
| Displaying Class Variables with Shape example
1 require 'Shape'
2 require 'Rectangle'
3
4 r1 = Rectangle.new(5,4,'blue','blue rectangle')
5 r1.display
6
7 r2 = Rectangle.new(3,6,'red','red rectangle')
8 r2.display
|
| |
| |
| |