Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Methods and Attributes in Ruby?

Tags:

Can you give me an example?

like image 929
collimarco Avatar asked Jul 28 '09 14:07

collimarco


People also ask

What is the difference between methods and attributes?

A method is a function defined in the class. An attribute is an instance variable defined in the class.

What is the difference between methods and data attributes of objects?

A data attribute is exactly as it sounds; it's data, it is simply a property. A method is a procedure, an action, and this is exactly what a method attribute is.

What are class attributes and methods?

A class is a kind of data type, just like a string, integer or list. When we create an object of that data type, we call it an instance of a class. The data values which we store inside an object are called attributes, and the functions which are associated with the object are called methods.

What is a Ruby method?

A method in Ruby is a set of expressions that returns a value. Within a method, you can organize your code into subroutines which can be easily invoked from other areas of their program. A method name must start a letter or a character with the eight-bit set.


1 Answers

Attributes are just a shortcut. If you use attr_accessor to create an attribute, Ruby just declares an instance variable and creates getter and setter methods for you.

Since you asked for an example:

class Thing     attr_accessor :my_property      attr_reader :my_readable_property      attr_writer :my_writable_property      def do_stuff         # does stuff     end end  

Here's how you'd use the class:

# Instantiate thing = Thing.new  # Call the method do_stuff thing.do_stuff  # You can read or write my_property thing.my_property = "Whatever" puts thing.my_property  # We only have a readable accessor for my_readable_property puts thing.my_readable_property   # And my_writable_propety has only the writable accessor thing.my_writable_property = "Whatever" 
like image 174
Rafe Avatar answered Sep 19 '22 00:09

Rafe