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

Intro to Mandarin (pinyin)

Xiansheng (Mr., husband, teacher) Ni hao (how do you do/ hello) Xiaojie (miss/ young lady) Qing (please) Wen (to ask) Nin (you-polite) Gui xing (what is your honorable surname?) Wo (I) Ne Jiao (to be called; to call) Shenme (what) Mingzi... Continue →