Understanding attr_accessor in a ruby Class
Below is a simple example for using attr_accessor in a ruby class.
attr_accessor is the property of an object. So, if server is a Class, the server's hostname can be is it's attribute or Property.
In the below example,
We are creating a class called "Person". Realistically, a Person can have a name, so name is a property or attribute of a person. Our object is a human being who belongs to a class called "Person", this object has a name, i.e. in real world A person with a name.
By using a Person's name (Object.attribute) you can address or call him ot greet him. This greeting or calling or addressing is called "Method" in ruby world ( only for this example's sake).
Let's walk thorugh the example
vim class.rb
class Person
attr_accessor :name
def greet
#{@name} says helloBelow is a simple example for using attr_accessor in a ruby class.
attr_accessor is the property of an object. So, if server is a Class, the server's hostname can be is it's attribute or Property.
In the below example,
We are creating a class called "Person". Realistically, a Person can have a name, so name is a property or attribute of a person. Our object is a human being who belongs to a class called "Person", this object has a name, i.e. in real world A person with a name.
By using a Person's name (Object.attribute) you can address or call him ot greet him. This greeting or calling or addressing is called "Method" in ruby world ( only for this example's sake).
Let's walk thorugh the example
vim class.rb
class Person
attr_accessor :name
def greet
end
end
attr_accessor is the Property of the object.
So, I create an Object with the Class.
Class here is "Person"
joe = Person.new
An object by the name "joe" is created.
:name is one of the attributes of the object "joe"
joe.name = "Tribiani"
Then we use this "Object.Attribute i.e. joe(object).name(attribute)" with a method.
Did we write any method i.e. function in the Class ? Yes we have i.e. is "greet"
So we call "Object.Attribute.Method" i.e. joe(object).name(attribute).greet(Method or Function)
How the output is seen
irb(main):001:0> require 'class.rb' # Ruby script written above
=> true
irb(main):002:0> joe = Person.new
=> #<0xb7c73cf8>
irb(main):003:0>
irb(main):003:0> joe.name="Tribiani" # Setting the name attribute for the object "joe"=> "Tribiani"
irb(main):004:0> joe.greet # joe(object).name(attribute).greet(Method or Function)=> "Tribiani says hello"
irb(main):005:0>0xb7c73cf8>
No comments:
Post a Comment