Saturday, March 12, 2016

how to define class and object in Ruby

        Hello friends as Ruby is pure object oriented language , How to define class in ruby and how to access the attributes is very import to learn.
Example lets consider Car class in ruby and speed, color and model as its attributes:
Example : code

irb(main):001:0> class Car
irb(main):002:1> attr_accessor :model,:color,:speed
irb(main):003:1> end

Here you can see using class keyword in ruby we can make class and all contain of class lies between class and end key word.
Car is name of class, and you can notice it nil  keyword shown by ruby interpreter. when class do not return anything nil is returned by it.








How to create object of class in ruby and how to use inheritance with ruby is very simple 
Example :code

irb(main):001:0> class Car
irb(main):002:1> attr_accessor :model,:company,:color
irb(main):003:1> end
=> nil
irb(main):004:0> c1=Car.new
=> #
irb(main):005:0> c1.model="swift"
=> "swift"
irb(main):006:0> c1.color="red"
=> "red"
irb(main):007:0> c1.company="maruti"
=> "maruti"
irb(main):008:0>
Object in ruby

here you can notice that c1 is object of class Car, so new keyword after class keyword with use of .(dot) 
c1 is object of Car class here is how we access the attributes of class.
attr_accessor is keyword used to declare the access to the attributes of class.







     Let see if we inherit property of Car class in Sport_car class: code

irb(main):008:0> class Sport_car < Car
irb(main):009:1> attr_accessor :topspeed
irb(main):010:1> end
=> nil
irb(main):011:0> s1=Sport_car.new
=> #
irb(main):012:0> s1.color="black"
=> "black"
irb(main):013:0> s1.topspeed=500
=> 500
irb(main):014:0>
OOps concept in Ruby

Here we can see with just use "<" and parent class Car we can inherit attributes of Car class in Sport_car class, and also we can add new attributes such as topspeed in sport_car class

No comments:

Post a Comment