DEV Community

Jeeho Lee
Jeeho Lee

Posted on

Some Ruby Details I Find Myself Tripping Up On

I found myself getting caught on what attributes specifically are and how they function separately from methods. Attributes are specific properties of an object and store data, while methods are functions that can be associated with the object and define the behavior/capabilities of the object.

Attributes created by attr_accessor basically declares an instance variable and creates getter and setter methods. The importance of this would be in access the variables outside the scope of the instance, since all instance variables are private by default.

For example, if I were to create an attribute of username in a class of my definition called Person, I can access the attribute by self.username or by @username when inside the scope of Person. However, when I go outside of the scope of Person (let's say I create Jeeho = Person.new), I cannot access the instance variable. With the getter/setter methods defined by the attribute, I can access outside Person (e.g. Jeeho.username). Here, I'm technically not calling object.attribute, but rather object.attribute_method.

class Person
  attr_accessor :username

  def example_method
    return self.username
    # having object self here might be helpful to distinguish from local variable if there's a local variable of the same name as the method
    # same result as just calling @username
  end
end

Jeeho = Person.new
# can't access instance variable @username here outside Person, but still can access it if I have a getter method defined, which attributes does for me
Jeeho.username

Enter fullscreen mode Exit fullscreen mode

Another detail of Ruby I was getting caught in was whether every method requires calling on an object. While object methods are referenced very clearly by object.method, it is still possible to create standalone methods that do not require an object (a good example of this being the square_root method that was in Defining our own classes Lesson).

def square_root(a_number)
  answer = a_number ** 0.5
  return answer
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)