classPoint attr_accessor:x attr_reader:y @@origin = 0 ORIGIN = 2 definitialize(x = 0, y = 0) @x, @y = x, y end defanother_method
end deffirst_quarant? x > 0 && y > 0 end def+(p2) Point.new(x + p2.x, y + p2.y) end defsecond_quarant?(x, y) x < 0 && y > 0 end class << self deffoo end defbar end defwat end end end
类的继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classPoint3D < Point definitialize(x = 0, y = 0, z = 0) @x, @y, @z = x, y, z end definitialize(x = 0, y = 0, z = 0) super(x, y) @z = z end definitialize(x = 0, y = 0, z = 0) super end end
模块
+ include:mixin module instance methods as class’ instance methods + extend:mixin module instance methods as class’ class methods
moduleHelper defshfit_right(x, y, z = 0) end defClassMethods defdistance(obj1, obj2) Math.sqrt((obj1.x - obj2.x)**2 + (obj1.y - obj2.y)**2) end end defself.included(klass) klass.extend ClassMethods end end
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
moduleLib BUCKETS = [0, 1000, 10_000, 50_000, 100_000] defannual_fee case balance when BUCKETS[0]...BUCKETS[1] 10 when BUCKETS[1]...BUCKETS[2] 5 when BUCKETS[2]...BUCKETS[3] 3 else 0 end end end
exception
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
deffactorial(n) raise TypeError unless n.is_a? Integer raise ArgumentError if n < 1 return1if n == 1 n * factorial(n-1) end
begin x = factorial(1) rescue ArgumentError => e puts 'try again with a value >= 1' rescue TypeError => e puts 'try again with an integer' else puts x ensure puts 'the process of factorial calculation is completed' end