Ruby class shortcuts

class Person
  attr_accessor :name, :age
end

# same as:

class Person
  def name
    @name 
  end

  def name=(name)
    @name = name
  end

  def age 
    @age
  end

  def age=(age)
    @age = age
  end 
end

Ruby is awesome. I think it has to do with the ease and beauty of Textmate but I really look forward to typing out code using the language. Additionally I’ve been introduced to many shortcuts which make writing code a lot easier.

One recent shortcut which I’ve been trying to wrap my head around is attraccessor. In the above code you will see the one line “attraccessor :name, :age” re-writes everything below.

It basically performs the read and write methods on a function. This allows you to call x.name and return whatever x is and also allows you to assign x.name = “Jahde”.

I’m sure I’ll be seeing other shortcuts that make writing code easier but this one stood out to me. I think I’m just shocked that 1 line can replace 12 but I’ve come to find this is one of the key attributes of programming itself. Ruby wants to make herself easy to love.

 
0
Kudos
 
0
Kudos

Now read this

Object feels and introspection

One of the most interesting concepts I’ve learned so far about the Ruby programming language is the idea of introspection. In computing, type introspection is the idea that an object or program knows about it’s own properties at runtime.... Continue →