Methods in Ruby

Ruby supports methods defined on struct-like objects called classes.

class Rect
  attr_accessor :width, :height

  def initialize(width, height)
    @width = width
    @height = height
  end

  # This `area` method is defined on the Rect class
  def area
    @width * @height
  end

  # Methods can be defined for instance objects
  def perim
    2 * @width + 2 * @height
  end
end

# Main execution
r = Rect.new(10, 5)

# Here we call the 2 methods defined for our class
puts "area: #{r.area}"
puts "perim: #{r.perim}"

# Ruby doesn't have pointers, but we can still create a reference to the same object
rr = r
puts "area: #{rr.area}"
puts "perim: #{rr.perim}"

To run the program:

$ ruby methods.rb
area: 50
perim: 30
area: 50
perim: 30

In Ruby, all methods are defined on classes or modules, and they always operate on the instance of the class (the object). There’s no need to explicitly define receiver types as in some other languages.

Ruby doesn’t have the concept of pointer and value types like some other languages. All variables in Ruby are references to objects. When you assign an object to a new variable or pass it to a method, you’re creating a new reference to the same object, not copying the object itself.

Next, we’ll look at Ruby’s mechanism for grouping and naming related sets of methods: modules and mixins.