Understanding Ruby classes


#1

Hey everyone,

I have been working through all of the ruby exercises and feel pretty comfortable with the language itself but I am having some issues understanding how classes work. Here is a solution to the 05_book_titles problem that I found. I understand what all the code is saying but I dont quite understand the following and why they are necessary:

  • @title
  • attr_accessor :title
class Book
# write your code here
  attr_accessor :title

  def title
    titleize(@title)
  end

  def titleize input
    little_words = %w(a an and if of to the but with in)
    input.capitalize.gsub(/(\w+)/) do |word|
      little_words.include?(word) ? word : word.capitalize
    end
  end
end

#2

@title is an instance variable. The ‘@’ is what makes it an instance variable, and thus visible everywhere in the object’s scope. Each instance of the class can have a different value for @title, for example, and this value can be accessed and changed anywhere within the instance. This also removes the need to pass such variables as arguments to methods within the instance (e.g. if you want to use @title in some_instance_method, you just use it in the method and do not need to pass it in by calling ‘some_instance_method(@title)’).

attr-accessor enables reading of, and writing to, the instance variable from ‘outside’ of the instance.

In your example you could, therefore, do:

$ my_book = Book.new
$ my_book.title = “My Groovy Title”

And the ‘my_book’ instance of the Book class would have its ‘@title’ instance variable set to “My Groovy Title”.

You could then also do:

$ my_var = my_book.title

And ‘my_var’ would have its value set to “My Groovy Title”.

attr_reader would allow only reading of the value from ‘outside’ of the instance.
attr_writer would allow only setting of the value from ‘outside’ of the instance.


#3

Thank you a lot! This really helped out. I feel like it was one of the best explanations that I have found on the web thus far.

This will likely take a bit of tooling around to really grasp but It helped enough for me to complete the next exercise. :slight_smile:


#4

You’re welcome! Great to hear it was helpful. :+1: