<

Majd's Blog

Ruby is a Class Act

3/26/15

>

What's going on here...:

class Wardrobe
  def initialize(type, color)
    @type = type
    @color = color
  end
  def type
    @type
  end
  def color
    @color
  end
end

This is a "class" in Ruby. Did you think I was going to talk about a classy person named Ruby? NO! You Git! Heheh. This is the basic structure for class. Which is used when you want to make multiple types of object that have the same other things going on like common methods and properties.

In the example above, we start by defining the class as Wardrobe. Note that it's capitalized, unlike other things in Ruby. That sets is apart as a class.

Next is initialize, which will start up anything in that method when you create a new object of that class. Here, it takes two parameters: type and color.

The next two method definitions, type, and color, simply call back the original word that was entered. That's where we COULD get complicated and be like "Take this and split up the characters and multiply and yadda yadda..." Basically where we would manipulate things if that's what we wanted to do.

Creating a new object with this class is easy. It's the next step:

cute_new_top = Wardrobe.new("shirt", "red")

This creates a new Object named cute_new_top that is a red shirt. Now we can call the little methods we wrote and it should give us back what put in, unchanged:

cute_new_top.type  =>"shirt"
cute_new_top.color =>"red"

I fudged this a little to make it clear. The arrows show you the output of what's plugged in. There is a shortcut to this so we don't have to define all of the variables, and that's done with attr_reader. Let's rewrite the code using it:

class Wardrobe
  attr_reader :type, :color
  def initialize(type, color)
    @type = type
    @color = color
  end
end

There! Much cleaner! All this does is it makes is so we can "read" the attribute by calling it like we did in the last example. There are two others we could do like this, and they are attr_writer and attr_accessor. The writer makes something that we can write to, and accessor does both reading AND writing. We don't always want to call up a variable or write to it, necessarily, so this provides us options that keeps everything organized. No examples for this here, but I think that's quite enough for now! Hope you had fun!